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.
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.
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.
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.
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With