Monday, April 14, 2008

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 numberdef bin2dec(number)   ret_dec = 0;   number.split(//).each{|digit|      ret_dec = (Integer(digit) + ret_dec) * 2;   }   return ret_dec/2;endprint bin2dec('101'),"\n";## OR you can use this one toonumber = "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 stringdef 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 HEXendprint dec2hex("255"),"\n";`
Conversion of decimal into binary format

`## Function to convert a given integer string/number into binary formatted stringdef 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;endprint dec2bin("19"),"\n";`
Conversion of Hex to Decimal number

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

`number = "255";print number.oct,"\n"; ## oct will convert into decimalprint 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. Edward Waller 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

Kasidit 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 ## 1
puts 11 ## 1
puts 11 ## 0
puts 11 ## 1
puts 11 ## 0 -- from this point - 0s

check my blog - scraping with ruby :)

http://rubyscraping.wordpress.com

Get function name programaticaly - Python

This little piece of code will help you to get the function name programatically. This is very helpful when you are implementing the debug...