3

I have a bmp file that I read in my Python program. Once I have read in the bytes, I want to do bit-wise operations on each byte I read in. My program is:

with open("ship.bmp", "rb") as f:
    byte = f.read(1)
    while byte != b"":
        # Do stuff with byte.
        byte = f.read(1)
    print(byte)

output:

b'\xfe' 

I was wondering how I can do manipulation on that? I.e convert it to bits. Some general pointers would be good. I lack experience with Python, so any help would be appreciated!

14
  • 1
    Is this Python 2 or 3? Looks like 3 but it's best to be sure, they're different in this case. Commented Jan 22, 2015 at 22:24
  • 2
    unrelated but you can change your while to a for loop for byte in iter(lambda:f.read(1),b"") Commented Jan 22, 2015 at 22:31
  • 1
    @PadraicCunningham Maybe he wants readability. Commented Jan 22, 2015 at 22:32
  • 1
    @mbomb007, unless you are stevie wonder that is readable Commented Jan 22, 2015 at 22:33
  • 1
    @PadraicCunningham It's definitely not as readable. Tons of languages have while loops. Not many have a function called iter or identical lambda syntax. Using a while is inherently easier to read and understand. Commented Jan 22, 2015 at 22:36

2 Answers 2

2

bytes objects yield integers from 0 through 255 inclusive when indexed. So, just perform the bit manipulation on the result of indexing.

3>> b'\xfe'[0]
254
3>> b'\xfe'[0] ^ 0x55
171
Sign up to request clarification or add additional context in comments.

2 Comments

A promt. The results wouldn't make sense otherwise
@Dunes: I modified my Python 3.x prompt so that I can easily differentiate between 3.x in one terminal and 2.x in another. The normal prompt in both is ">>> "
2

file.read(1) constructs a length 1 bytes objects, which is a bit overkill when you want the byte as an integer. To access each byte as an integer the following would be more succinct, and have the benefit of using a for loop.

with open("ship.bmp", "rb") as f:
    byte_data = f.read()

for byte in byte_data:
    # do stuff with byte. eg.
    result = byte & 0x2
    ...

4 Comments

Thanks, if i wanted to access the bits of a byte, how could i do that?
byte = 7;index = 7;bit = (byte << index >> 7) % 2;print bit
Or, if you want the 0th bit to be the bit on the far right, use byte << 7-index >> 7 instead.
I had to use % 2 because Python doesn't include unsigned right shift, since it doesn't have unsigned numbers.

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.