Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,684 questions

55,436 answers

573 users

How to convert a number to any base in Ruby

1 Answer

0 votes
def to_base(n, base)
  digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"

  raise "Base must be between 2 and 36" if base < 2 || base > 36
  return "0" if n == 0

  result = ""

  while n > 0
    remainder = n % base
    result << digits[remainder]
    n /= base
  end

  result.reverse
end

# Main program
begin
  number = 255

  puts "#{number} in base 2  = #{to_base(number, 2)}"
  puts "#{number} in base 8  = #{to_base(number, 8)}"
  puts "#{number} in base 16 = #{to_base(number, 16)}"
  puts "#{number} in base 36 = #{to_base(number, 36)}"
rescue => e
  puts "Error: #{e.message}"
end


# run:
#
# 255 in base 2  = 11111111
# 255 in base 8  = 377
# 255 in base 16 = FF
# 255 in base 36 = 73
#

 



answered Jul 7 by avibootz
...