Wednesday, March 25, 2009

Binary conversion in Ruby

We hardly stretch ourselves to limit unless situation demands to do so.

My requirement - convert a decimal to binary conversion

My first impression - there would be a to_b default method available in ruby which I can use straight away. But it was not so.

But as always it is quite simple to do it in ruby,

number.to_s(2)

gives the binary equivalent of the number

try this from ur IRB

3.to_s(2)

similarly for any base conversion just pass the base value to to_s

Example

3.to_s(10) for base 10 conversion.

No comments: