[New-bugs-announce] [issue40322] struct.pack adding unexpected byte in 'B' format

Robert Bressan report at bugs.python.org
Sat Apr 18 14:49:39 EDT 2020


New submission from Robert Bressan <robert.bressan at gmail.com>:

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'
¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯

----------
components: Interpreter Core
messages: 366734
nosy: Robert Bressan
priority: normal
severity: normal
status: open
title: struct.pack adding unexpected byte in 'B' format
type: behavior
versions: Python 3.8

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue40322>
_______________________________________


More information about the New-bugs-announce mailing list