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?
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.
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.
Solution 1. int intValue = 2; byte byteValue = Convert. ToByte(intValue);
>>> struct.unpack('>q', s)[0]
511
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With