开发者

Shortest way to convert these bytes to int in python?

开发者 https://www.devze.com 2023-01-30 14:36 出处:网络
I\'m converting the following string to it\'s unsigned integer representation: str = \'\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\xFF\'

I'm converting the following string to it's unsigned integer representation:

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

I can use struct.unpack('8B', str) to get the tuple representation (0,0,0,0,0,0,1,255), but what's the quickest/easiest way to convert this tuple to an int?

Right now, my code is

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

But this is long and ugly, for such a simple function! There must be a better 开发者_运维技巧way! Can any SO python gurus help me to trim this down and python-ify it?


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


Just unpack as a long long (64-bit integer):

struct.unpack('>Q', str)

Q = unsigned long long. Switch to q if the string represents a signed long long.

The > indicates big-endian byte order. Use < to indicate little-endian byte order.


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

Struct can deal with 8-byte long longs directly.


Have to agree with the long and ugly comment. Totally ignoring the struct.unpack Q/q option:

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

The second-last line could have used bit-bashing operators:

r = (r << 8) | b
0

精彩评论

暂无评论...
验证码 换一张
取 消