0

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.

3
  • As a string- bin(int.from_bytes(bytes_read, "big"))[2:]. If you want a list of ints, just map(int, ...) that Commented Jan 11, 2023 at 20:11
  • 1
    What is fetch(b) supposed to do? Commented Jan 11, 2023 at 20:16
  • Yes, there are 8 bits in a byte. Commented Jan 11, 2023 at 20:18

3 Answers 3

1

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
Sign up to request clarification or add additional context in comments.

Comments

0

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')

Comments

0

To literally get a list of 0 or 1 for each byte of the file is simple:

[(n >> i) & 0x01 for n in bytes_read for i in range(7,-1,-1)]

Realize that this is going to be a very long list.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.