basher
basher

Reputation: 139

array of bytes to num

I have for example

tab = [0x51, 0x3c, 0xb8, 0x15]

then I want to convert this table to integer

0x15b83c51 = 363323840

any ideas?

Upvotes: 0

Views: 140

Answers (4)

scuawn
scuawn

Reputation: 106

Possible solution:

> tab.reverse.inject("") {|s,a| s<<a.to_s(16) }.to_i(16)
 => 364395601 

Upvotes: 1

hrnt
hrnt

Reputation: 10142

(I have no idea how you get 363323840 from 0x15b83c51. Like other people already answered, 0x15b83c51 is 364395601)

Here is yet another solution, which also works if you have more than one integer to decode in your table.

# Convert to binary string
binaryString = [0x51, 0x3c, 0xb8, 0x15].map(&:chr).join 

# Convert the binary string to an unsigned integer array
# and take its first element 
number = binaryString.unpack("I").first 

Upvotes: 0

DNNX
DNNX

Reputation: 6255

tab.reverse.inject {|s,a| (s<<8) + a}
# => 364395601

Upvotes: 0

Denis de Bernardy
Denis de Bernardy

Reputation: 78561

I'm not very familiar with the bit/hex functions in ruby, so sorry if it's not more specific or precise, but... have you tried to:

bitnum = 0
while hexnum = tab.pop do
  # 1. convert hexnum to binary format
  # 2. bit-shift bitnum accordingly
end

Upvotes: 0

Related Questions