bit manipulation in CircuitPython

Question:

I’ve to perform bit-level operations using CircuitPython, like extracting and manipulating 3 bits from a bytes() object.

In normal Python I use the Bitarray library.
Is there an equivalent for CircuitPython?

Thanks.

Asked By: mik3.rizzo

||

Answers:

Even with regular Python it’s typical to use the bitwise & and | operators and the bitwise shift operators for setting/selecting various bits. E.g., to test the 6th bit of an integer value:

if myValue & 0b100000:
  print('bit 6 was set')
else:
  print('bit 6 was not set')

To set bits 4-6:

myValue |= 0b111000

To extract bits 4-6:

extract = (myValue & 0b111000) >> 3

Etc.

Answered By: larsks