Reputation:
Why does python return "odd values" when I try packing a float
object? For example:
>>> import struct,time
>>> struct.pack('d', time.time())
b'\xe0LC|\xf6l\xd7A'
>>> struct.unpack('d', b'\xe0LC|\xf6l\xd7A')
(1572067825.051567,)
Why does it unpack the value as a tuple instead of a float? And then, why does it use values such as LC
and |
and l
-- I thought it would pack the items in hex?
Upvotes: 1
Views: 865
Reputation: 1827
The documentation of unpack states explicitly that the result is a tuple:
Unpack from the buffer buffer (presumably packed by pack(format, ...)) according to the format string format. The result is a tuple even if it contains exactly one item. The buffer’s size in bytes must match the size required by the format, as reflected by calcsize().
You can see the representations of all possible bytes with:
for i in range(256):
print("{} : {}".format(i, bytes([i])))
For instance, 124
is represented by b'|'
. In your case, b'\xe0LC|\xf6l\xd7A'
is the representation of bytes([224, 76, 67, 124, 246, 108, 215, 65])
.
Upvotes: 1