QUERY · ISSUE
struct.pack doesn't check for value bounds
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
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.
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.
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).
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.
Such code is fully compatible with CPython.