Converting a byte_array to signed int

The official pyboard running MicroPython.
This is the reference design and main target board for MicroPython.
You can buy one at the store.
Target audience: Users with a pyboard.
Post Reply
Iyassou
Posts: 42
Joined: Sun Jun 26, 2016 9:15 am

Converting a byte_array to signed int

Post by Iyassou » Sun Jul 10, 2016 9:26 am

Hello,

I'm reading a 16-bit value from two consecutive registers on a sensor and I've put them into one variable by typing

Code: Select all

data = bytearray(i2c.mem_read(2, addr, mem_addr))
and I want to turn this into a signed integer.
The order in which I'm reading the values defines data's endianness as little. So far in my previous code I've been using

Code: Select all

int.from_bytes(bytearray, 'little')
to convert a bytearray of little endianness into an integer.
The Python documentation for int.from_bytes (available here https://docs.python.org/3/library/stdty ... from_bytes) says that you can specify the signed or unsigned nature of the bytearray (or byte(s)) to be converted. So I typed

Code: Select all

int.from_bytes(data, 'little', True)
but I got this error

Code: Select all

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: function expected at most 3 arguments, got 4
Does anyone know a workaround or another way to convert a bytearray into a signed integer?

User avatar
deshipu
Posts: 1388
Joined: Thu May 28, 2015 5:54 pm

Re: Converting a byte_array to signed int

Post by deshipu » Sun Jul 10, 2016 1:44 pm

Code: Select all

import ustruct

data = ustruct.unpack("<h", i2c.mem_read(2, addr, mem_addr))[0]

Iyassou
Posts: 42
Joined: Sun Jun 26, 2016 9:15 am

Re: Converting a byte_array to signed int

Post by Iyassou » Tue Jul 12, 2016 5:06 pm

Sorry for the late reply, Internet was down. Thanks that did the job perfectly!

Post Reply