Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: How to convert a list of integers into a hexadecimal string?

Tags:

ruby

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?

like image 552
Cisplatin Avatar asked Nov 16 '25 23:11

Cisplatin


1 Answers

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.

like image 113
Stefan Avatar answered Nov 18 '25 19:11

Stefan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!