問題:我想得到(7,5,3) => 000001110000010100000011 => 460035 also the converse, i.e., 460035 => 000001110000010100000011 => (7,5,3)這是我嘗試過的程序:L=(7,5,3) # here L may vary each time.a=0for i in range(3): a=bin(a << 8) ^ bin(L[i])print a 但它給出了錯誤TypeError: unsupported operand type(s) for ^: 'str' and 'str'我該怎么做?
2 回答

呼如林
TA貢獻1798條經(jīng)驗 獲得超3個贊
沒有必要重新發(fā)明輪子。如果您看到了我在評論中提供的文檔鏈接,您可以在那里找到這些有用的方法:int.from_bytes
和int.to_bytes
. 我們可以這樣使用它們:
input = (7, 5, 3)
result = int.from_bytes(input, byteorder='big')
print(result)
>>> 460035
print(tuple(result.to_bytes(3, byteorder='big')))
>>> (7, 5, 3)

小怪獸愛吃肉
TA貢獻1852條經(jīng)驗 獲得超1個贊
您應(yīng)該對數(shù)字而不是轉(zhuǎn)換后的字符串執(zhí)行位操作:
L=(7,5,3)
a=0
for i in L:
a <<= 8
a |= i
print(bin(a), a)
這輸出:
0b1110000010100000011 460035
逆轉(zhuǎn):
a = 460035
L = []
while True:
L.append(a & 0xff)
a >>= 8
if not a:
break
L = tuple(L[::-1])
print(L)
這輸出:
(7, 5, 3)
添加回答
舉報
0/150
提交
取消