In python, how do I convert a list of bytes into a uniform list of bits (0s and 1s)…
- User
In python, how do I convert a list of bytes into a uniform list of bits (0s and 1s) representing the initial bytes?
- Assistant
You can convert a list of bytes into bits in Python by first converting each byte to its binary representation using the
bin()function, then removing the '0b' prefix, and padding each binary number with 0s to ensure it has 8 bits. Finally, concatenate all the binary numbers into a single list of bits.Here is an example code:
pythonbyte_list = [0b11010110, 0b00101111, 0b10101000, 0b01010101] bit_list = [] for b in byte_list: binary = bin(b)[2:].zfill(8) bit_list += [int(i) for i in binary] print(bit_list)Output:
code[1, 1, 0, 1, 0, 1, 1, 0, 0, 0, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1]In the example above, the
bin()function converts each byte in thebyte_listto its binary representation. The[2:]slice removes the first two characters of the string (which are '0b', indicating that it's a binary number).