# Convert binary to decimal and hex numbers

Discussion in 'Ruby' started by Todd Gardner, Jun 19, 2004.

1. ### Todd GardnerGuest

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, Jun 19, 2004

2. ### Tim BatesGuest

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, Jun 19, 2004

3. ### Todd GardnerGuest

Tim Bates <> wrote in message news:<>...
> 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

Todd Gardner, Jun 21, 2004