I am writing a python3 script to write some numbers as binary on file. While doing it I found something quite strange. for example, the following python code writes a "unsign short" and a "float" number to tmp file:
import struct
with open('tmp', "wb") as f:
id1 = 1
i = 0.5785536878880112
fmt = "Hf"
data = struct.pack('Hf', id1, i)
f.write(data)
print("no. of bytes:%d"%struct.calcsize(fmt))
According to the docs "H" (unsigned short) is 2 bytes and "f"(float) is 4 bytes. so I'd expect a 6-byte file, however the output is a 8byte data:
01 00 00 00 18 1c 14 3f
as indicated by
struct.calcsize(fmt)
which says "Hf" is of 8 bytes in size
if I do it separately, e.g.
data = struct.pack('H', id1)
f.write(data)
data = struct.pack('f', i)
f.write(data)
then the output is an expected 6-byte file:
01 00 18 1c 14 3f
what is happening here?