Converting a binary value to hexadecimal in Ruby
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/