I have a situation where I need to convert a binary value to hex in Ruby. My situation is as 开发者_StackOverflow中文版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.
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/
Both String#to_i
and Integer#to_s
take an optional integer argument specifying the base. So you can convert your binary string to an integer using base 2 and then convert that integer back to a string using base 16.
You can use the unpack
method on string pointing the target to be hex
def bin_to_hex(binary_string)
binary_string.unpack('H*').first
end
Refer to: https://apidock.com/ruby/String/unpack
I found it to be much more clean than the solutions listed above.
as state above by @Michael Kohl easiest way, define method with the action
# if you don't want the output to be 0x.. but just 0.. leave out the first x in the format string.
def self.bin_to_hex(string)
"0x%02x" % "#{string}".to_i(2)
end
and use the method like this
string = "00011110"
puts bin_to_hex(string)
=> 0x1e
remember these are still ASCII representations, in case you want to encode it and send bytes as HEX (send via UDP or low level protocols) just do:
value = self.bin_to_hex(value)
bytes = [value]
bytes.pack('H*' * bytes.size)
精彩评论