Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

More elegant way to convert 4 bytes to 32bit integer

Tags:

ruby

I'm converting arrays consisting of four byte values to 32bit numbers by executing the following code:

a = [0, 16, 82, 0]
i = a.map { |e| "%02x" % e }.join.to_i(16)
# => 1069568

It works as intended, but I wonder if there's a more elegant way to perform this task. Maybe not utilizing strings.

like image 580
verm-luh Avatar asked Nov 16 '25 16:11

verm-luh


1 Answers

Using pack and unpack1:

a = [0, 16, 82, 0]

a.pack('C4').unpack1('L>')
#=> 1069568

C4 means 8-bit unsigned (4 times) and L> means 32-bit unsigned (big endian).

However, pack returns a binary string, so this is not string-free.

like image 160
Stefan Avatar answered Nov 19 '25 08:11

Stefan