This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Author Robert Bressan
Recipients Robert Bressan
Date 2020-04-18.18:49:39
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <1587235779.35.0.377995541073.issue40322@roundup.psfhosted.org>
In-reply-to
Content
struct.pack() is adding an unexpected null byte.

When I've run this code:
___________________________________________
import struct
d = {'c':b'a', 'b':1, 'B':1, '?':False, 'h':2, 'H':2, 'i':-3, 'I':3, 'l':4, 'L':4, 'q':5, 'Q':5, 'f':100.0, 'd':2.0}

for x in d:
    y = struct.pack(x,d[x])
    print('len('+x+') = ' + str(len(y)) + ': ' + str(y))

x = struct.pack('fBHL', 100, 1, 2,4)
print('len(fBHL) = ' + str(len(x)) + ': ' +  str(x))
¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯

I got this return:
___________________________________________
len(c) = 1: b'a'
len(b) = 1: b'\x01'
len(B) = 1: b'\x01'
len(?) = 1: b'\x00'
len(h) = 2: b'\x02\x00'
len(H) = 2: b'\x02\x00'
len(i) = 4: b'\xfd\xff\xff\xff'
len(I) = 4: b'\x03\x00\x00\x00'
len(l) = 4: b'\x04\x00\x00\x00'
len(L) = 4: b'\x04\x00\x00\x00'
len(q) = 8: b'\x05\x00\x00\x00\x00\x00\x00\x00'
len(Q) = 8: b'\x05\x00\x00\x00\x00\x00\x00\x00'
len(f) = 4: b'\x00\x00\xc8B'
len(d) = 8: b'\x00\x00\x00\x00\x00\x00\x00@'
len(fBHL) = 12: b'\x00\x00\xc8B\x01\x00\x02\x00\x04\x00\x00\x00'
¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯
I believe the last line pack ("fBHL") consumes 11 bytes (4+1+2+4), and analysing the bytearray, the B is packing 2 bytes, instead of one. My expected result was:
___________________________________________
len(fBHL) = 11: b'\x00\x00\xc8B\x01\x02\x00\x04\x00\x00\x00'
¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯
History
Date User Action Args
2020-04-18 18:49:39Robert Bressansetrecipients: + Robert Bressan
2020-04-18 18:49:39Robert Bressansetmessageid: <1587235779.35.0.377995541073.issue40322@roundup.psfhosted.org>
2020-04-18 18:49:39Robert Bressanlinkissue40322 messages
2020-04-18 18:49:39Robert Bressancreate