亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何將字節元組轉換為整數并返回?

如何將字節元組轉換為整數并返回?

守候你守候我 2021-06-29 13:18:13
問題:我想得到(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條經驗 獲得超3個贊

沒有必要重新發明輪子。如果您看到了我在評論中提供的文檔鏈接,您可以在那里找到這些有用的方法:int.from_bytesint.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)


查看完整回答
反對 回復 2021-07-06
?
小怪獸愛吃肉

TA貢獻1852條經驗 獲得超1個贊

您應該對數字而不是轉換后的字符串執行位操作:


L=(7,5,3)

a=0

for i in L:

    a <<= 8

    a |= i

print(bin(a), a)

這輸出:


0b1110000010100000011 460035

逆轉:


a = 460035

L = []

while True:

    L.append(a & 0xff)

    a >>= 8

    if not a:

        break

L = tuple(L[::-1])

print(L)

這輸出:


(7, 5, 3)


查看完整回答
反對 回復 2021-07-06
  • 2 回答
  • 0 關注
  • 233 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號