Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shortest way to convert these bytes to int in python?

Tags:

python

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?

like image 968
linked Avatar asked Dec 13 '10 20:12

linked


People also ask

How do you convert to bytes in Python?

We can use the built-in Bytes class in Python to convert a string to bytes: simply pass the string as the first input of the constructor of the Bytes class and then pass the encoding as the second argument. Printing the object shows a user-friendly textual representation, but the data contained in it is​ in bytes.

What is Bytestring in Python?

In Python, a byte string is just that: a sequence of bytes. It isn't human-readable. Under the hood, everything must be converted to a byte string before it can be stored in a computer. On the other hand, a character string, often just called a "string", is a sequence of characters. It is human-readable.

How do you convert int to byte value?

Solution 1. int intValue = 2; byte byteValue = Convert. ToByte(intValue);


1 Answers

>>> struct.unpack('>q', s)[0]
511
like image 130
Ignacio Vazquez-Abrams Avatar answered Sep 28 '22 12:09

Ignacio Vazquez-Abrams