Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a binary value to hexadecimal in Ruby

Tags:

ruby

hex

binary

I have a situation where I need to convert a binary value to hex in Ruby. My situation is as follows:

When bin = "0000111", my output should be: hex = "07".

When bin = "010001111", my output should be: hex = "08f".

Could someone help me out on how to do this? Thanks in advance.

like image 883
sundar Avatar asked May 18 '11 06:05

sundar


People also ask

How do I convert text to number in Ruby?

Converting Strings to Numbers Ruby provides the to_i and to_f methods to convert strings to numbers. to_i converts a string to an integer, and to_f converts a string to a float.

Can hex convert to binary directly?

Thus, the conversion of hexadecimal to binary is very important. Here it is not possible to convert it directly, we will convert hexadecimal to decimal then that decimal number is converted to binary.


2 Answers

How about:

>> "0x%02x" % "0000111".to_i(2) #=> "0x07"
>> "0x%02x" % "010001111".to_i(2) #=> "0x8f"

Edit: if you don't want the output to be 0x.. but just 0.. leave out the first x in the format string.

like image 60
Michael Kohl Avatar answered Sep 25 '22 18:09

Michael Kohl


def bin_to_hex(s)
    s.each_byte.map { |b| b.to_s(16).rjust(2,'0') }.join
end

Which I found here (with zero padding modifications):

http://anthonylewis.com/2011/02/09/to-hex-and-back-with-ruby/

like image 27
odigity Avatar answered Sep 21 '22 18:09

odigity