How do I convert part of a python tuple (byte array) into an integer

Would,

num = (response[0] << 24) + (response[1] << 16) + (response[2] << 8) + response[3]

meet your needs?

aid


See Convert Bytes to Floating Point Numbers in Python

You probably want to use the struct module, e.g.

import struct

response = (0, 0, 117, 143, 6)
struct.unpack(">I", ''.join([chr(x) for x in response[:-1]]))

Assuming an unsigned int. There may be a better way to do the conversion to unpack, a list comprehension with join was just the first thing that I came up with.

EDIT: See also ΤΖΩΤΖΙΟΥ's comment on this answer regarding endianness as well.

EDIT #2: If you don't mind using the array module as well, here is an alternate method that obviates the need for a list comprehension. Thanks to @JimB for pointing out that unpack can operate on arrays as well.

import struct
from array import array

response = (0, 0, 117, 143, 6)
bytes = array('B', response[:-1])
struct.unpack('>I', bytes)

OK, You don't specify the endinanness or whether the integer is signed or and it (perhaps) is faster to with the struct module but:

b = (8, 1, 0, 0)
sum(b[i] << (i * 8) for i in range(4))

Tags:

Python

Tuples