I connect by i2c a module BN0055 (magnetic,gyro,acceleration) to my pyboard.
Repeatedly i want to read the course, 2 bytes with low byte first and high byte next. I do this with
i2c.read(2,40,0x1A) and get for instance b'\xc7\x14'. The 2 hex bytes have to be switched and converted to decimal.
For switching I read the bytes in a bytearray. Then my problem starts, I dont know how to convert that to decimal.
part of the code:
x=bytearray(i2c.mem_read(2,40,0x1A)) #read
z=x[1];x[1]=x[0];x[0]=z #switch
I tried int('x',16) but that wont do #convert
a=x[1]; b=x[0]
int('ab'),16 but that gives not the right answer because a and b are decimals.
Python is new for me, possibly there is a simple solution but I don't see it.
converting bytearray
- pythoncoder
- Posts: 5956
- Joined: Fri Jul 18, 2014 8:01 am
- Location: UK
- Contact:
Re: converting bytearray
The Python struct module is your friend. As an example
Code: Select all
>>> from struct import unpack
>>> a = bytearray(b'\xc7\x14')
>>> unpack('<H', a)[0]
5319
>>> hex(5319)
'0x14c7'
>>>
Peter Hinch
Index to my micropython libraries.
Index to my micropython libraries.
Re: converting bytearray
So, you could do it the old fashioned way: or alternatively:
You could also use: and a little example done on the REPL:
Code: Select all
num = x[0] * 256 + x[1]
Code: Select all
num = x[0] << 8 | x[1]
Code: Select all
import usruct as struct
(num,) = struct.unpack('>h', x)
Code: Select all
>>> import ustruct as struct
>>> x = bytearray((1,2))
>>> (num,) = struct.unpack('>h', x)
>>> num
258
>>> hex(num)
'0x102'
>>> num = x[0] * 256 + x[1]
>>> num
258
>>> num = x[0] << 8 | x[1]
>>> num
258