Convert binary to decimal and hex numbers

T

Todd Gardner

Hello everyone,

I would like to convert binary numbers to decimal and hex numbers.

For example,
0b1010 = 0d55 = 0xA

Even more generic, would be a way to convert base n to base m.

Where can I go to find how to do this with one single method call?

Thank you,

Todd
 
T

Tim Bates

Todd said:
Even more generic, would be a way to convert base n to base m.

Where can I go to find how to do this with one single method call?

When you're dealing with numbers internally to Ruby, it doesn't matter
at all what base you use.
myvar += 0x0a
is exactly equivalent to
myvar += 10
The only time it makes any difference is when you're reading them in or
printing them out, so what you really want is a way to convert String
representations in different bases to Fixnums and vice versa. Thus, the
methods you're looking for are
String#to_i(base=10)
and
Fixnum#to_s(base=10)

For example:
irb(main):001:0> "10".to_i
=> 10
irb(main):002:0> "10".to_i(16)
=> 16
irb(main):003:0> "10".to_i(2)
=> 2
irb(main):004:0> 10101.to_s
=> "10101"
irb(main):005:0> 10101.to_s(2)
=> "10011101110101"
irb(main):006:0> 10101.to_s(16)
=> "2775"
irb(main):007:0> 10101.to_s(27)
=> "dn3"

Tim.
 
T

Todd Gardner

Tim Bates said:
When you're dealing with numbers internally to Ruby, it doesn't matter
at all what base you use.
myvar += 0x0a
is exactly equivalent to
myvar += 10
The only time it makes any difference is when you're reading them in or
printing them out, so what you really want is a way to convert String
representations in different bases to Fixnums and vice versa. Thus, the
methods you're looking for are
String#to_i(base=10)
and
Fixnum#to_s(base=10)

For example:
irb(main):001:0> "10".to_i
=> 10
irb(main):002:0> "10".to_i(16)
=> 16
irb(main):003:0> "10".to_i(2)
=> 2
irb(main):004:0> 10101.to_s
=> "10101"
irb(main):005:0> 10101.to_s(2)
=> "10011101110101"
irb(main):006:0> 10101.to_s(16)
=> "2775"
irb(main):007:0> 10101.to_s(27)
=> "dn3"

Tim.

Hello Tim,

Thanks for showing me that! I think I've got it now.

Todd
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,013
Latest member
KatriceSwa

Latest Threads

Top