4

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?

Cisplatin
  • 2,860
  • 3
  • 36
  • 56

2 Answers2

13

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.

Stefan
  • 109,145
  • 14
  • 143
  • 218
4

I would do something like this:

array = [0, 128, 255]
array.map { |number| number.to_s(16).rjust(2, '0') }.join
#=> "0080ff"
spickermann
  • 100,941
  • 9
  • 101
  • 131