How to convert part of python tuple (byte array) to integer

I am trying to talk with a device using python. I was given a tuple of bytes that contains storage information. How to convert data to correct values:

response = (0, 0, 117, 143, 6)

The first 4 values ​​are a 32-bit int, indicating how many bytes were used, and the last value is a percentage value.

I can access the tuple as the answer [0], but I can’t understand how I can get the first 4 values ​​in the required int.

+7
python tuples
source share
6 answers

See Convert bytes to floating point numbers in Python

You probably want to use a structural module like

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

Assuming an unsigned int. Perhaps the best way to do the conversion for decompression, understanding the list using a join was the first thing I came up with.

EDIT . See also Ξ€Ξ–Ξ©Ξ€Ξ–Ξ™ΞŸΞ₯ comment on this answer regarding judgment.

EDIT No. 2 . If you don't mind using an array module, this is an alternative method that eliminates the need for list comprehension. Thanks @ JimB , pointing out that unpacking can work on arrays too.

 import struct from array import array response = (0, 0, 117, 143, 6) bytes = array('B', response[:-1]) struct.unpack('>I', bytes) 
+11
source share

Will it,

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

satisfy your needs?

help

+13
source share

OK. You do not indicate whether a limb is specified or whether an integer is signed or whether it is (possibly) faster using the struct module, but:

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

You can also use an array module

 import struct from array import array response = (0, 0, 117, 143, 6) a = array('B', response[:4]) struct.unpack('>I', a) (30095L,) 
+4
source share

It seems to work to reduce!

What you basically need is a bit shift of a byte at a time, and then add (add) the next byte in the sequence.

 a = (0, 0, 117, 143, 6) reduce(lambda x, y: (x<<8) + y, a) 7704326 
+2
source share

How to use the map function:

 a = (0, 0, 117, 143, 6) b = [] map(b.append, a) 

In addition, I do not know if this is what you are looking for:

 response = (0, 0, 117, 143, 6) response[0:4] 
0
source share

All Articles