mirror of
https://github.com/micropython/micropython.git
synced 2025-07-21 21:11:12 +02:00
Fixes and improvements to `int.to_bytes()` are: - No longer overflows if byte size is 0 (closes #13041). - Raises OverflowError in any case where number won't fit into byte length (now matches CPython, previously MicroPython would return a truncated bytes object). - Document that `micropython int.to_bytes()` doesn't implement the optional signed kwarg, but will behave as if `signed=True` when the integer is negative (this is the current behaviour). Add tests for this also. Requires changes for small ints, MPZ large ints, and "long long" large ints. Adds a new set of unit tests for ints between 32 and 64 bits to increase coverage of "long long" large ints, which are otherwise untested. Tested on unix port (64 bit small ints, MPZ long ints) and Zephyr STM32WB board (32 bit small ints, long long large ints). This work was funded through GitHub Sponsors. Signed-off-by: Angus Gratton <angus@redyak.com.au>
63 lines
1.4 KiB
Python
63 lines
1.4 KiB
Python
import sys
|
|
|
|
print((2**64).to_bytes(9, "little"))
|
|
print((2**64).to_bytes(9, "big"))
|
|
|
|
b = bytes(range(20))
|
|
|
|
il = int.from_bytes(b, "little")
|
|
ib = int.from_bytes(b, "big")
|
|
print(il)
|
|
print(ib)
|
|
print(il.to_bytes(20, "little"))
|
|
print(ib.to_bytes(20, "big"))
|
|
|
|
# check padding comes out correctly
|
|
print(il.to_bytes(40, "little"))
|
|
print(ib.to_bytes(40, "big"))
|
|
|
|
# check that extra zero bytes don't change the internal int value
|
|
print(int.from_bytes(b + bytes(10), "little") == int.from_bytes(b, "little"))
|
|
|
|
# can't write to a zero-length bytes object
|
|
try:
|
|
ib.to_bytes(0, "little")
|
|
except OverflowError:
|
|
print("OverflowError")
|
|
|
|
# or one that it too short
|
|
try:
|
|
ib.to_bytes(18, "big")
|
|
except OverflowError:
|
|
print("OverflowError")
|
|
|
|
# negative representations
|
|
|
|
# MicroPython int.to_bytes() behaves as if signed=True for negative numbers
|
|
if "micropython" in repr(sys.implementation):
|
|
|
|
def to_bytes_compat(i, l, e):
|
|
return i.to_bytes(l, e)
|
|
else:
|
|
# Implement MicroPython compatible behaviour for CPython
|
|
def to_bytes_compat(i, l, e):
|
|
return i.to_bytes(l, e, signed=i < 0)
|
|
|
|
|
|
print(to_bytes_compat(-ib, 20, "big"))
|
|
print(to_bytes_compat(ib * -ib, 40, "big"))
|
|
|
|
# case where an additional byte is needed for sign bit
|
|
ib = (2**64) - 1
|
|
print(ib.to_bytes(8, "little"))
|
|
|
|
ib *= -1
|
|
|
|
try:
|
|
print(to_bytes_compat(ib, 8, "little"))
|
|
except OverflowError:
|
|
print("OverflowError")
|
|
|
|
print(to_bytes_compat(ib, 9, "little"))
|
|
print(to_bytes_compat(ib, 9, "big"))
|