0

I am trying to open a file in binary mode so that I can manipulate it at a bit level.

I am trying to obtain the binary information with:

with open('file.txt', 'rb') as f:
    data = f.read()

but when I try to print this out I get a mixture of hex and some strange (to me) characters like the following

...~\xeb\xdd{\xdf\xba\xf7^\xf7\xee\xbd\xd7\...

how do I obtain the binary information as 0's and 1's with the ability to change 0110 1001 into 1001 0110

3
  • Why do you want to manipulate at the binary level? What are you trying to achieve with that? Commented Jul 25, 2015 at 6:39
  • I am currently studying cryptography and would like to implement what I am learning in code Commented Jul 25, 2015 at 6:41
  • See How I can read a bit in Python? Commented Jul 25, 2015 at 9:44

1 Answer 1

0

Binary data is just numbers. What's more, Python pretty much treats a boolean or a byte the same way as an int. Using BytesIO will let you access the file as a stream of numbers, each representing a byte.

To input a number in base 2, use the 0b00000000 syntax. To view the number in the same way, use "{:08b}".format(number). And to change 0b01101001 into 0b10010110, use ~0b01101001 & 0xFF. The ~ operator flips the bits, while the & 0xFF is just a mask to zero the remaining 24 bits from the int. (That's necessary because since we flipped all 32 bits, all those leading 0s are now 1s, and we don't want that at all).

Sign up to request clarification or add additional context in comments.

2 Comments

thanks, this has helped a lot, though if for example I want to change flip one single bit "{:08b}".format(number) results in a string which is not mutable. is there a different way of doing this to allow single bit manipulation?
You have to understand that the string representation is aimed at you as the user. To Python, the numbers are always just bits. If you want to flip a bit, use XOR (^). 255 ^ 1 is exactly the same as 0b11111111 ^ 0b00000001, or for that matter 0xFF ^ 0x01. It flips the last bit, and the result is 0b11111110, or 254 or any other way you can think of to represent that number. There are plenty of other bitwise operators too.

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.