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?
Asked
Active
Viewed 1,956 times
4

Cisplatin
- 2,860
- 3
- 36
- 56
-
Does something like this help? http://stackoverflow.com/questions/84421/converting-an-integer-to-a-hexadecimal-string-in-ruby?rq=1 – Antonio Nov 18 '16 at 17:15
-
`arr.map { |n| n.to_s(16) }.join('')` – Dave Newton Nov 18 '16 at 17:17
-
@Antonio I saw that, but it would convert characters like `1` to `1` instead of `01`, which is an issue because each element represents two hexadecimal characters. – Cisplatin Nov 18 '16 at 17:22
-
2`arr.map { |n| sprintf('%02x', n) }.join('')` – Dave Newton Nov 18 '16 at 17:28
-
...or a variant of @Dave's #2: `[0, 128, 255].each_with_object('') { |n,s| s << "%02x" % n } #=> "0080ff"` or `..(."%02x" % n).upcase..` if `=> "0080FF"` is desired. – Cary Swoveland Nov 18 '16 at 19:58
2 Answers
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
-
This is roughly twice as fast as the other answer, if speed is important. – zetetic Nov 18 '16 at 19:55
-
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