Home > Net >  How to get a list of all of the bits from a binary file in python
How to get a list of all of the bits from a binary file in python

Time:01-12

So i have a binary file - i need all of the bits in that file in a list. I know that using the Rb function when opening the file gets all of the bytes like this:


 with open("binaryfile.bin", "rb") as f:
        bytes_read = f.read()
        for b in bytes_read:
            fetch(b)

But i was wondering if there was a way I could get all of the specific bits in this binary file - and put it in a list.

I know python can only do it via bytes. How do I split it up into bits? (i believe there are 8 bits per byte, correct?)

Thanks!

I tried using the rb function but that only works with bytes, not bits.

CodePudding user response:

You can use bitwise comparisons to isolate specific bits in a byte.

Want to find out if the 3rd bit in a byte is 1 or 0? Simply do a bitewise "and" operation with 0b100.

>>> 4 & 0b100
4
>>> 3 & 0b100
0

CodePudding user response:

You can use the bin() function to retrieve the binary digits that correspond to a byte.

with open("binaryfile.bin", "rb") as f:
    bytes_read = f.read()
    for b in bytes_read:
        bits = bin(b)
        print(bits)

Note that this will likely print a large amount of binary digits. You could instead store them in a list, if you wish.

Also note that you can remove the 0b portion of the string that results from bin() so you are only dealing with the bits themselves instead of python's bitstring representation. Finally, you can pad the bits so they are byte aligned (8 bits total).

Consider the following solution which converts the bytes of a file into bit strings of length 8 and appends each bit string to a list.

bit_array = []
with open("binaryfile.bin", "rb") as f:
    bytes_read = f.read()
    for b in bytes_read:
        bit_array.append(bin(b)[2:].rjust(8,'0')
  • Related