converting bytearray

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
Hansg
Posts: 4
Joined: Fri Sep 11, 2015 12:58 pm

converting bytearray

Post by Hansg » Fri Sep 11, 2015 1:44 pm

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.

User avatar
pythoncoder
Posts: 5956
Joined: Fri Jul 18, 2014 8:01 am
Location: UK
Contact:

Re: converting bytearray

Post by pythoncoder » Fri Sep 11, 2015 4:09 pm

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.

User avatar
dhylands
Posts: 3821
Joined: Mon Jan 06, 2014 6:08 pm
Location: Peachland, BC, Canada
Contact:

Re: converting bytearray

Post by dhylands » Fri Sep 11, 2015 4:23 pm

So, you could do it the old fashioned way:

Code: Select all

num = x[0] * 256 + x[1]
or alternatively:

Code: Select all

num = x[0] << 8 | x[1]
You could also use:

Code: Select all

import usruct as struct
(num,) = struct.unpack('>h', x)
and a little example done on the REPL:

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

Post Reply