function int.from_bytes Different results

General discussions and questions abound development of code with MicroPython that is not hardware specific.
Target audience: MicroPython Users.
Post Reply
arthurj58
Posts: 1
Joined: Tue Dec 10, 2019 9:02 pm

function int.from_bytes Different results

Post by arthurj58 » Tue Dec 10, 2019 9:14 pm

Hi

I fetch Bluetooth data Convert to int

os mac / python 3.7.3
int.from_bytes(b'\x8c\x7b\xd3\x3c', byteorder='big', signed=True)
-1938042052

os MicroPython v1.11-624-g210d05328 / python 3, 4, 0
int.from_bytes(b'\x8c\x7b\xd3\x3c', 'big', True)
2356925244

MicroPython ouput value
Not what I want
How to get -1938042052

thank

User avatar
jimmo
Posts: 2754
Joined: Tue Aug 08, 2017 1:57 am
Location: Sydney, Australia
Contact:

Re: function int.from_bytes Different results

Post by jimmo » Wed Dec 11, 2019 2:42 am

MicroPython doesn't currently support the "signed" parameter to from_bytes.

In the code for from_bytes it says:

Code: Select all

    // TODO: Support signed param (assumes signed=False at the moment)
    (void)n_args;
So it matches the CPython behavior if you set signed=False (which probably isn't what you want).

However, the workaround is to use struct.unpack instead

Code: Select all

>>> struct.unpack('>i', b'\x8c\x7b\xd3\x3c')
(-1938042052,)
(Note that unpack returns a single-element tuple here).

Post Reply