![](/img/trans.png)
[英]TypeError: bad operand type for unary +: 'str' in string creation
[英]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(^)
運算符。 異或的真值表如下所示:
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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.