Need elegant way to cast four bytes into a long
grante at visi.com
Fri Aug 8 17:53:41 CEST 2003
In article <3f33c209$1 at news.si.com>, 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));
Bad C programming. Your program isn't portable.
> I have been getting what I want in this sort of manner :
> l = 0L
> l = a
> l += a << 8
> l += a << 16
> l += a << 24
> but I think that's too wordy. Is there a more intrinsic and elegant way
> to do this?
How about this:
l = a + (a<<8) + (a<<16) + (a<<24)
Or you can use struct:
l = struct.unpack("<I","".join([chr(b)for b in a]))
I think that the former is more obvious.
Grant Edwards grante Yow! I always liked FLAG
More information about the Python-list