← index #5427Issue #6477
Duplicate · high · value 5.710
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.pack doesn't error on overflow

openby CarlFKopened 2020-09-23updated 2024-09-13
bug

" But in this case, it does seem like a bit of a bug that should also be fixed in MicroPython."
https://forum.micropython.org/viewtopic.php?f=12&t=9061&sid=61e7d19e860522ffa52fa6ceaa927f65#p51114

the corresponding CircuitPython commit is: https://github.com/adafruit/circuitpython/commit/095c844004bcd8680a4bf68901adbd9cac6a4302

Python 3.6.9 (default, Jul 17 2020, 12:50:27) 
>>> import struct
>>> struct.pack("H", 65536)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
struct.error: ushort format requires 0 <= number <= (0x7fff * 2 + 1)

Adafruit CircuitPython 5.3.1 on 2020-07-13; Adafruit CircuitPlayground Express with samd21g18
>>> import struct
>>> struct.pack("H", 65536)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
OverflowError: value must fit in 2 byte(s)

MicroPython v1.13 on 2020-09-07; Adafruit Feather STM32F405 with STM32F405RG
Type "help()" for more information.
>>> import struct
>>> struct.pack("H", 65536)
b'\x00\x00'

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