tags:

views:

3719

answers:

6

I am trying to talk to a device using python. I have been handed a tuple of bytes which contains the storage information. How can I convert the data into the correct values:

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

The first 4 values are a 32-bit int telling me how many bytes have been used and the last value is the percentage used.

I can access the tuple as response[0] but cannot see how I can get the first 4 values into the int I require.

+5  A: 

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)
Jay
I would suggest that the pack format be ">I" i.e. big endian; 0x0000758f (30095₁₀) for a random count of bytes seems more likely than 0x8f750000 (2406809600₁₀)
ΤΖΩΤΖΙΟΥ
+3  A: 

Would,

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

meet your needs?

aid

+3  A: 

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))
+3  A: 

You could also make use of the array module

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

(30095L,)
JimB
I tried out this approach too, but decided to go with a list comprehension and join() instead, to avoid importing another module, and since neither was particularly clear, unfortunately.
Jay
I forgot that struct can pack arrays [fixed answer], which I think makes this version slightly better than the list comp.
JimB
Nice, I didn't know it could do that, missed that in the docs. I'll add it to my answer also as an alternate.
Jay
A: 

How about using the map function:

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

Also, I don't know if this is you are looking for:

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

Dear all, what if I need to convert a float into 4 bytes?

Javier
Please create your own question, this isn't a traditional forum
Phil Hannent