Convert binary to decimal and hex numbers

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

Todd Gardner wrote:

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.

ยทยทยท

--
Tim Bates
tim@bates.id.au

Tim Bates <tim@bates.id.au> wrote in message news:<40D42FA6.5000001@bates.id.au>...

Todd Gardner wrote:
> 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.

Hello Tim,

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

Todd