TypeError: bad operand type for unary ~: 'bytes' : complement of a string of bytes

TypeError: bad operand type for unary ~: 'bytes' : complement of a string of bytes

我正在尝试计算此字节字符串的补码:

bts = b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\x01'

我试过使用波浪号 ~bts 但我有 TypeError: bad operand type for unary ~: 'bytes'.

我也试过用

import bitarray
~bitarray.bitarray(bts)

它似乎可以工作,但后来我不得不再次将它转换为字节字符串。所以我想到的唯一解决方案如下:

bts2 = bytes([0 if b == 1 else 1 for b in bts])

是否有更好的方法来计算补码?

使用 tobytes()bitarray 转换回 bytes

(~bitarray.bitarray(bts)).tobytes()

not怎么样?

>>> bytes(not b for b in bts)
b'\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x00\x00'

(与您的工作版本相同的结果)

您也可以使用 xor(^) 运算符。 xor 的真相 table 如下所示:

x    y  |  q
0    0  |  0 
0    1  |  1 
1    0  |  1 
1    1  |  0 

xor 有 2 个特征:第一个 a^1 = ~a 和第二个 a^0 = a 所以如果你对一个位进行 xor 1 它将被反转。 在 python 中,我们可以通过多种方式做到这一点:

bytes(x^1 for x in bts)

bytes(map(lambda x:x^1, bts))

您也可以使用以下代码 not 字节中的第 n 位:

bytes(x^(1<<n) for x in bts)

对于一个字节中的一位,您也可以使用 subtraction

bytes(1-x for x in bts)