1

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?

asked May 3, 2020 at 21:05
2
  • 1
    What is your expected outcome for that? Is that 8 a fixed amount, or could it be 2, 29, 33, or -1? Commented May 3, 2020 at 21:11
  • bits is not a fixed amount, but in my case it is usually 8, however in_buf_word is the thing that would be sort of dynamic. Commented May 3, 2020 at 21:14

3 Answers 3

1
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())
answered May 3, 2020 at 21:59
Sign up to request clarification or add additional context in comments.

2 Comments

how would i convert it back to bytes ?
@EmilBengtsson use tobytes(). see edited answer for example
0

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]
answered May 3, 2020 at 21:28

Comments

0

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'
answered May 3, 2020 at 21:50

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.