【问题标题】:Bitwise operations on byte string and int字节字符串和整数的按位运算
【发布时间】:2020-08-18 06:03:49
【问题描述】:

我正在将一些 cython 代码转换为 python 的过程中,它进展顺利,直到我开始按位运算。这是代码的sn-p:

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

如果我运行它,它会吐出这个错误:

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

我将如何解决这个问题?

【问题讨论】:

  • 您对此的预期结果是什么? 8 是固定金额,还是 22933-1
  • bits 不是一个固定的数量,但在我的情况下它通常是 8,但是 in_buf_word 是一种动态的东西。

标签: python python-2.7 bitwise-operators bitstring


【解决方案1】:

右移8位就是把最右边的字节删掉。

由于您已经有一个bytes 对象,这可以更轻松地完成:

in_buf_word = in_buf_word[:-1]

【讨论】:

    【解决方案2】:

    您可以通过将字节转换为整数,对其进行移位,然后将结果转换回字节字符串来实现。

    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'
    

    【讨论】:

      【解决方案3】:
      import bitstring
      
      in_buf_word = b'\xff\xff\xff\xff\x00'
      bits = 8
      in_buf_word  = bitstring.BitArray(in_buf_word ) >> bits
      

      如果你没有。转到您的终端

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

      要将其转换回字节,请使用 tobytes() 方法:

      print(in_buf_word.tobytes())
      

      【讨论】:

      • 如何将其转换回字节?
      • @EmilBengtsson 使用 tobytes()。例如查看编辑的答案
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-21
      • 2010-11-05
      • 2015-05-07
      • 1970-01-01
      • 2014-04-08
      • 1970-01-01
      相关资源
      最近更新 更多