Need elegant way to cast four bytes into a long

Alex Martelli aleax at
Fri Aug 8 18:30:46 CEST 2003

William S. Huizinga wrote:

> I've got an array.array of unsigned char and would like to make a slice
> of that array (e.g. a[0:4]) become one long like I would in "C" :
> l = ((unsigned long *) (&a[0]))[0];

What about:

b = array.array('L')
l = b[0]

I think this should faithfully reproduce the endianness-related
unportability of that C fragment (cannot necessarily reproduce
crashes due to possible use of misaligned pointers, though:-).

Actually, I believe you do not really need the .tostring call
in modern Python -- just b.fromstring(a[0:4]) should be
equivalent (and faster).  Better, if you need to transform
into longs _many_ adjacent segments of 4 bytes each, this
approach does generalize, and speed is good.  Finally, you
can remedy endianness issue with the .byteswap method...


More information about the Python-list mailing list