Python byte array to bit array
That will work:
def access_bit(data, num):
base = int(num // 8)
shift = int(num % 8)
return (data[base] >> shift) & 0x1
If you'd like to create a binary array you can use it like this:
[access_bit(data,i) for i in range(len(data)*8)]
If you would like to have the bits string, or to spare yourself from creating a function, I would use format() and ord(), let me take a simpler example to illustrate
bytes = '\xf0\x0f'
bytes_as_bits = ''.join(format(ord(byte), '08b') for byte in bytes)
This should output: '1111000000001111'
If you want LSB first you can just flip the output of format(), so:
bytes = '\xf0\x0f'
bytes_as_bits = ''.join(format(ord(byte), '08b')[::-1] for byte in bytes)
This should output: '0000111111110000'
Now you want to use b'\xf0\x0f'
instead of '\xf0\x0f'
. For python2 the code works the same, but for python3 you have to get rid of ord() so:
bytes = b'\xf0\x0f'
bytes_as_bits = ''.join(format(byte, '08b') for byte in bytes)
And flipping the string is the same issue.
I found the format() functionality here. And the flipping ([::-1]) functionality here.