pythonpython-2.7bitwise-operatorsbitstring

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?


Solution

  • 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())