Ruby: Number conversion from one base to another

Most of the cases I didn't find any library that converts a given number from one base to another. I'm giving description about converting number from decimal to hexadecimal, or octal to binary etc base conversion with example.

Conversion of a binary number into decimal format.

## Function to convert a given binary string into decimal number
def bin2dec(number)
   ret_dec = 0;
   number.split(//).each{|digit|
      ret_dec = (Integer(digit) + ret_dec) * 2;
   }
   return ret_dec/2;
end
print bin2dec('101'),"\n";

## OR you can use this one too
number = "1111";
print Integer("0b"+number), "\n"; ## appending 0b will work for binary

Conversion of a decimal number into hexa decimal format

## Function to convert a given integer string/number into hexa decimal string
def dec2hex(number)
   number = Integer(number);
   hex_digit = "0123456789ABCDEF".split(//);
   ret_hex = '';
   while(number != 0)
      ret_hex = String(hex_digit[number % 16 ] ) + ret_hex;
      number = number / 16;
   end
   return ret_hex; ## Returning HEX
end
print dec2hex("255"),"\n";

Conversion of decimal into binary format

## Function to convert a given integer string/number into binary formatted string
def dec2bin(number)
   number = Integer(number);
   if(number == 0)
      return 0;
   end
   ret_bin = "";
   ## Untill val is zero, convert it into binary format
   while(number != 0)
      ret_bin = String(number % 2) + ret_bin;
      number = number / 2;
   end
   return ret_bin;
end
print dec2bin("19"),"\n";

Conversion of Hex to Decimal number

number = "FF";
print number.hex,"\n"; ## This will convert a hexa string into int
print Integer("0x"+number), "\n"; ## this will work too

Conversion of octal into decimal number

number = "255";
print number.oct,"\n"; ## oct will convert into decimal
print Integer("0o"+number), "\n"; ## appending 0o will work too

Using the provided examples, you can easily convert the other base conversion task easily. If anyone know the ruby library that can do the task with a single function call, pls post at comment section.

Comments

Anonymous said…
you can use

>> "101".to_i(2)
=> 5

and

>> 5.to_s(2)
=> "101"

to convert to other bases pretty easily (the base is the argument)

See
http://www.ruby-doc.org/core/classes/String.html#M000802
Unknown said…
Thanks so much for sharing the bin2dec and dec2hex functions! I was just looking for something like this - very beneficial - thanks very very much!
Petko said…
another two neat tricks:

puts 0b1011 ## 11
puts 11[0] ## 1
puts 11[1] ## 1
puts 11[2] ## 0
puts 11[3] ## 1
puts 11[4] ## 0 -- from this point - 0s

check my blog - scraping with ruby :)

http://rubyscraping.wordpress.com