1

I am a beginner and I am trying to perform bit wise operations on an element from 'byte' array

Example code:

step1_result[i] = (bytes((seedrandom[i] >> 3)) | bytes((seedrandom[i] << 5)))
>>> TypeError: unsupported operand type(s) for >>: 'bytes' and 'bytes'

step1_result and seedrandom is a list with 'byte' type elements

Is there a specific method to apply bitwise operations on a byte in Python?

3
  • 2
    Show the offending line, please, your code does not use >>.bytes can be thought of as a list of characters, so shifting that by other bytes is undefined. Commented Nov 15, 2019 at 7:25
  • Code has been updated Commented Nov 15, 2019 at 7:28
  • There still is no >> with two bytes as operands in that code. Commented Nov 15, 2019 at 7:31

2 Answers 2

4

Python's bitwise operators only operate on integers, so you need to convert each byte to an int before performing a bitwise operation.

import sys
b1, b2 = [b'\x77', b'\x88']
int.from_bytes(b1, sys.byteorder) << int.from_bytes(b2, sys.byteorder)

Note that explicit conversion is not necessary if your bytes are in an actual bytearray, because indexing on a bytearray returns ints.

ba = bytearray(b'\x77\x01')
ba[0] << ba[1]

Likewise if the bytes are in a composite bytes object

bs = b'\x77\x01'
bs[0] << bs[1]
Sign up to request clarification or add additional context in comments.

Comments

1

bytes is an immutable sequence type, not a numeric type. Did you mean an elementwise operation, such as bytes(map(lambda x: (x<<3) & 0xff, b'\xff\x03')) (list comprehension form: bytes([(x<<3) & 0xff for x in b'\xff\x03']))? Note that bytes can't exceed 255, so I needed to mask to 8 bits before collecting it in a second bytes object. Python doesn't have a standard type for a singular byte, just as it doesn't have one for a singular character. If you read a single element from a bytes object that byte is converted into an int.

2 Comments

I want to do bitwise operations and i want the operations on '8 bits' bytes. Since, by default size is taken as 128bits, output is not coming as expected.
Where did you get 128 from? Python supports arbitrarily large integers.

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.