verm-luh
verm-luh

Reputation: 184

More elegant way to convert 4 bytes to 32bit integer

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.

Upvotes: 3

Views: 525

Answers (2)

Stefan
Stefan

Reputation: 114248

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.

Upvotes: 6

sawa
sawa

Reputation: 168249

If you have one byte, that would be the result as is. If you add one byte to the right side, that would make the original result move two positions to the left (which means multiplying by 0x100, or 16 ** 2 = 256), and add the new byte. You can repeat this as many times as there are bytes.

a.inject{|acc, byte| acc * 0x100 + byte}
# => 1069568

Upvotes: 5

Related Questions