簡體   English   中英

在python中將這些字節轉換為int的最短方法?

[英]Shortest way to convert these bytes to int in python?

我正在將以下字符串轉換為無符號整數表示:

str = '\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\xFF'

我可以使用struct.unpack('8B', str)來獲取元組表示(0,0,0,0,0,0,1,255) ,但是將這個元組轉換為int的最快/最簡單的方法是什么?

現在,我的代碼是

def unpack_str(s):
  i = r = 0
  for b in reversed(struct.unpack('8B', s)):
    r += r*2**i
    i++
  return r

但這很長很丑,對於這么簡單的功能! 肯定有更好的辦法! 任何SO python大師都可以幫我修剪它和python-ify嗎?

>>> struct.unpack('>q', s)[0]
511

只需解壓縮為長(64位整數):

struct.unpack('>Q', str)

Q =無符號長多。 如果字符串表示有符號的長q則切換到q

>表示big-endian字節順序。 使用<表示little-endian字節順序。

def unpack_str(bytes):
  return struct.unpack('<q',bytes)

Struct可以直接處理8字節長的long。

不得不同意long and ugly評論。 完全忽略struct.unpack Q / q選項:

def unpack_str(s):
  r = 0
  for b in struct.unpack('8B', s):
    r = r * 256 + b
  return r

倒數第二行可能使用了bit-bashing運算符:

r = (r << 8) | b

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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