簡體   English   中英

TypeError:一元的錯誤操作數類型〜:'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(^)運算符。 異或的真值表如下所示:

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM