Emil Bengtsson
Emil Bengtsson

Reputation: 13

Bitwise operations on byte string and int

i am in the process of converting some cython code to python, and it went well until i came to the bitwise operations. Here is a snippet of the code:

in_buf_word = b'\xff\xff\xff\xff\x00'
bits = 8
in_buf_word >>= bits

If i run this it will spit out this error:

TypeError: unsupported operand type(s) for >>=: 'str' and 'int'

how would i fix this?

Upvotes: 1

Views: 926

Answers (3)

Jackson
Jackson

Reputation: 1223

import bitstring

in_buf_word = b'\xff\xff\xff\xff\x00'
bits = 8
in_buf_word  = bitstring.BitArray(in_buf_word ) >> bits

If you dont have it. Go to your terminal

pip3 install bitstring --> python 3
pip install bitstring --> python 2

To covert it back into bytes use the tobytes() method:

print(in_buf_word.tobytes())

Upvotes: 1

martineau
martineau

Reputation: 123423

You can do it by converting the bytes into an integer, shifting that, and then converting the result back into a byte string.

in_buf_word = b'\xff\xff\xff\xff\x00'
bits = 8

print(in_buf_word)  # -> b'\xff\xff\xff\xff\x00'
temp = int.from_bytes(in_buf_word, byteorder='big') >> bits
in_buf_word = temp.to_bytes(len(in_buf_word), byteorder='big')
print(in_buf_word)  # -> b'\x00\xff\xff\xff\xff'

Upvotes: 0

mkrieger1
mkrieger1

Reputation: 23150

Shifting to the right by 8 bits just means cutting off the rightmost byte.

Since you already have a bytes object, this can be done more easily:

in_buf_word = in_buf_word[:-1]

Upvotes: 0

Related Questions