Search code examples
pythonmicropythonadafruit-circuitpython

bit manipulation in CircuitPython


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.


Solution

  • 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.