Jon Muyer
Jon Muyer

Reputation: 11

Pack and unpack a pair of integers to hex

I have a pair of 32 bit integers in Little-Endian format and i have to transform in hexadecimal value and reverse the process. I know how to transform to hexadecimal but i have problems to turn back to integer.

h = [15325,24748]

i = h.pack("S*").unpack('N*').first
 => 3711675488 

hex-value = i.to_s(16)
 => "dd3bac60" 

Now, how can i transform "dd3bac60" back to [15325,24748] ?

Thanks

Upvotes: 1

Views: 440

Answers (1)

Neil Slater
Neil Slater

Reputation: 27207

Just do everything in reverse order, and invert your pack/unpack logic:

hex_string = "dd3bac60"
[hex_string.to_i(16)].pack('N*').unpack('S*')
  => [15325, 24748]

Explanation: Each function you apply in your forward transformation has an inverse, so just apply them in reverse order:

  • String#to_i( base ) is inverse of Integer.to_s( base )
  • Array#pack('N*') is inverse of String#unpack('N*')
  • String#unpack('S*') is inverse of Array#pack('S*')

Upvotes: 1

Related Questions