Jordan
Jordan

Reputation: 4628

Different integers derived from the same Python byte string

>>> import binascii, struct
>>> foo_hex = 'b1e92555'
>>> foo_bin = binascii.unhexlify(foo_hex)
>>> int(foo_hex, 16)
2984846677
>>> struct.unpack('i', foo_bin)[0]
1428548017

Why are these integers different? Which method is correct and how can the other one be changed to be correct?

Upvotes: 0

Views: 51

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1122372

struct is interpreting the value using little-endian notation, while using unhexlify and int(.., 16) interprets it as a big-endian unsigned integer.

Use < or > to specify the endianness of your input, and use I to interpret it as a signed int:

>>> struct.unpack('>I', foo_bin)[0]
2984846677
>>> struct.unpack('<I', foo_bin)[0]
1428548017

See the Byte Order, Size and Alignment section of the struct documentation page.

Upvotes: 4

Related Questions