Reputation: 2998
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?
Upvotes: 4
Views: 2181
Reputation: 114218
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.
Upvotes: 13
Reputation: 107037
I would do something like this:
array = [0, 128, 255]
array.map { |number| number.to_s(16).rjust(2, '0') }.join
#=> "0080ff"
Upvotes: 4