4 bytes to int

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Mon Mar 19 04:41:53 CET 2007


En Sun, 18 Mar 2007 23:04:44 -0300, Andres Martinelli <andmarti at gmail.com>  
escribió:

> My simple question is:
> I have an array of 4 bytes, and I want to convert it to the int they  
> form.

You can use the struct module:

py> struct.unpack("i", "\x00\x00\x01\x00")
(65536,)

That's good if you have a string to start from. If your "array of 4 bytes"  
is actually an array.array object, you can get the string using the  
tostring method.
If your 4 bytes are in another format, maybe this function is more  
convenient:

py> def int_from_bytes(b3, b2, b1, b0):
...   "Builds an unsigned int (32bits) from 4 bytes, b3 being the most  
significa
nt byte"
...   return (((((b3 << 8) + b2) << 8) + b1) << 8) + b0
...
py> int_from_bytes(0, 0, 0, 0)
0
py> int_from_bytes(0, 0, 0, 10)
10
py> int_from_bytes(0, 0, 1, 0)
256
py> int_from_bytes(0, 0, 255, 255)
65535
py> int_from_bytes(127, 255, 255, 255)
2147483647
py> int_from_bytes(255, 255, 255, 255)
4294967295L

-- 
Gabriel Genellina




More information about the Python-list mailing list