← index #5427Issue #145
Related · high · value 0.992
QUERY · ISSUE

struct.pack doesn't check for value bounds

openby dimpoloopened 2019-12-16updated 2019-12-19
py-core

Setup: MicroPython v1.11-555-g80df377e9 on 2019-11-04; PYBv1.1 with STM32F405RG

struct.pack('B', 256)  # returns b'\x00'

CPython errors out with struct.error: ubyte format requires 0 <= number <= 255

CANDIDATE · ISSUE

Struct unpacking and pad bytes

closedby Snigelsonopened 2017-01-16updated 2017-01-17

In CPython, when unpacking structs with pad bytes the pad bytes generate no output. Example:

Python 3.4.2 (default, Oct  8 2014, 10:45:20)
[GCC 4.9.1] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import struct
>>> struct.unpack('>BxB', b'@_!')
(64, 33)

However, in Micropython they do. Example:

MicroPython v1.8.1-156-gf3636a7 on 2016-08-18; linux version
Use Ctrl-D to exit, Ctrl-E for paste mode
>>> import struct
>>> struct.unpack('>BxB', b'@_!')
(64, 0, 95)

Also, I just noticed the byte is not skipped.

3 comments
dpgeorge · 2017-01-17

The struct module does not support padding bytes. And in this case it's not raising an error to tell you that, but silently unpacking a null value.

Snigelson · 2017-01-17

That wouldn't be a problem for me, if it also advanced to the next byte, i.e. last example above returned (64,0,33).

pfalcon · 2017-01-17

https://github.com/micropython/micropython/commit/af9046193148084f008501434e4c9f49fedc053f makes sure that exception is consistently raised on unsupported typecodes.

@Snigelson , MicroPython doesn't support "x" typecode. You can work that around using "b" typecode, e.g.

a, dummy, b = struct.unpack('>BbB', b'@_!')

Such code is fully compatible with CPython.

Keyboard

j / / n
next pair
k / / p
previous pair
1 / / h
show query pane
2 / / l
show candidate pane
c
copy suggested comment
r
toggle reasoning
g i
go to index
?
show this help
esc
close overlays

press ? or esc to close

copied