I have an array of integers that range from 0 to 255, each representing two hexadecimal digits. I want to convert this array into one hexadecimal string using Ruby. How would I do that?
With pack and unpack: (or unpack1 in Ruby 2.4+)
[0, 128, 255].pack('C*').unpack('H*')[0]
#=> "0080ff"
[0, 128, 255].pack('C*').unpack1('H*')
#=> "0080ff"
The actual binary hexadecimal string is already returned by pack('C*'):
[0, 128, 255].pack('C*')
#=> "\x00\x80\xFF"
unpack('H*') then converts it back to a human readable representation.
A light-weight alternative is sprintf-style formatting via String@% which takes an array:
'%02x%02x%02x' % [0, 128, 255]
#=> "0080ff"
x means hexadecimal number and 02 means 2 digits with leading zero.
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