Understanding Python's struct pack/unpack functions

Viewed 369

I am working on project which includes usage of struct module and its pack/unpack functions with python3.6

I have referred to many articles like this one and have got the basic idea but I am not able to understand it for my use case.

For ex:

var = struct.pack('i',1) 
print(var) 

It gives output b'\x01\x00\x00\x00' which I can understand because we have mentioned int as format and thus output is of 4 bytes.

Now another example:

var = struct.pack('i', 1156888062)

Now in this case why is the output b'\xfe\xb5\xf4D'. Can anyone please explain this.

Also when I unpack it

print(struct.unpack('f', var))

How come the output is (1957.687255859375,)

1 Answers
>>> struct.pack('i', 1156888062)
b'\xfe\xb5\xf4D'

This is still four bytes, it's just that one of those bytes is a printable ASCII character D so it's displaying as that instead of as \x44. It's only a different representation. Proof:

>>> len(b'\xfe\xb5\xf4D')
4
>>> b'\x44'
b'D'

For the last bit, you need to unpack using the same format specifier you packed as. You're asking to interpret those same four bytes as a float, so obviously it'll give you a different result. Change it to 'i' and it'll work as expected:

>>> struct.unpack('f', var)
(1957.687255859375,)
>>> struct.unpack('i', var)
(1156888062,)    
Related