← index #15399PR #16798
Likely Duplicate · high · value 2.606
QUERY · ISSUE

int.to_bytes and int.from_bytes: signed parameter not implemented

openby Brun059opened 2024-07-03updated 2024-08-28
bugpy-core

Port, board and/or hardware

esp32-WROOM

MicroPython version

MicroPython v1.23.0 on 2024-06-02; Generic ESP32 module with ESP32

Reproduction

in micropython

int.from_bytes(b'\xFF\xFF' , 'big' , True)   --->  65535

in Python 3.11.4

int.from_bytes(b'\xFF\xFF' , byteorder='big' , signed=True)   ---> -1

Expected behaviour

Expected to return -1
according to https://docs.python.org/3/library/stdtypes.html#int.from_bytes

Observed behaviour

returns 65535 which is equivalent to signed=False

Additional Information

No, I've provided everything above.

Code of Conduct

Yes, I agree

CANDIDATE · PULL REQUEST

WIP py/objint.c: Add `signed` param to int.from_bytes().

openby IhorNehrutsaopened 2025-02-22updated 2025-08-19
py-core

Summary

Support signed=True param:
result = int.from_bytes(bytearray(), byteorder='big'|'little', signed=False|True)

>>> int.from_bytes(b'\xff', byteorder='little', signed=False)
255
>>> int.from_bytes(b'\xff', byteorder='little', signed=True)
-1
>>> 

Testing

test_int.py
Added:
micropython/tests/basics/int_from_bytes.py

Tested on ESP32, ESP32-S2 boards.

Trade-offs and Alternatives

The length of the byte array is limited to sizeof(mp_longint_impl_t) in this PR.
int.from_bytes(bytes(20)) will raise OverflowError: big-int overflow

Wait for #16311

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