6

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?

2
  • psst! Your function will always return zero! Can you see why? Commented Dec 13, 2010 at 20:19
  • Also, i++ is invalid syntax (as opposed to the equally meaningless, but more sneaky ++i which runs but doesn't do anything).
    – user395760
    Commented Dec 13, 2010 at 20:20

4 Answers 4

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

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.

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

Struct can deal with 8-byte long longs directly.

2
  • Thanks for the reply, but in practice, your "<" seems to be incorrect (gives me an answer in the millions, I assume this is for a signed longlong?)
    – linked
    Commented Dec 13, 2010 at 20:19
  • 1
    @linked: < is for little-endian (i.e. rightmost bit is most most significant), > is for big-endian (i.e. leftmost bit is most significant). q is for (signed) long long.
    – user395760
    Commented Dec 13, 2010 at 20:22
0

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.