bitarrays for upython... anyone doing it

General discussions and questions abound development of code with MicroPython that is not hardware specific.
Target audience: MicroPython Users.
User avatar
Roberthh
Posts: 3667
Joined: Sat May 09, 2015 4:13 pm
Location: Rhineland, Europe

Re: bitarrays for upython... anyone doing it

Post by Roberthh » Mon Sep 24, 2018 4:06 pm

Trust the error message. In the REPL version, you combine two int with &, in the script version, it is a bytes object and int.
Try in the script:
value[0] & 2**bit

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

Re: bitarrays for upython... anyone doing it

Post by dhylands » Mon Sep 24, 2018 7:51 pm

In your output it printed:

Code: Select all

val b'\x07' bit 2
but in your manual example you assigned value 7 rather than b'\x07'. If you try what your code actually printed, then you should see the error:

Code: Select all

>>> value = b'\x07'
>>> bit = 0x02
>>> bit_val = value & 2**bit
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported types for __and__: 'bytes', 'int'
In Python, you can use the ord function to convert from a string or bytestring into an interger value (edit: or as Robert-hh suggests, use the subscript): https://docs.python.org/3/library/functions.html#ord

Code: Select all

>>> value = ord(b'\x07')
>>> value
7
>>> bit = 0x02
>>> bit_val = value & 2**bit
>>> bit_val
4
You probably got the b'\x07' by reading from I2C, SPI, or UART?

Aside: rather than using 2**bit, it's more typical to use (1<<bit) (and alot more efficient).

Delebel
Posts: 48
Joined: Thu May 25, 2017 2:21 pm
Contact:

Re: I'm learning to get snaky...

Post by Delebel » Tue Sep 25, 2018 12:37 am

Thanks the ord() function did it. I added value = ord(value) and bingo. I also will be using the 1<<bit as opposed to 2**bit cause efficiency matters to me. Thanks again guys good work... ;)

Post Reply