Need elegant way to cast four bytes into a long

Max M maxm at mxm.dk
Sun Aug 10 14:26:36 EDT 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];
> 
> I have been getting what I want in this sort of manner :
> 
> 	l  = 0L
> 	l  = a[0]
> 	l += a[1] <<  8
> 	l += a[2] << 16
> 	l += a[3] << 24
> 
> but I think that's too wordy.  Is there a more intrinsic and elegant way 
> to do this?


def readBew(value):
     "Reads string as big endian word, (asserts len(string) in [1,2,4])"
     return unpack('>%s' % {1:'b', 2:'H', 4:'l'}[len(value)], value)[0]

def writeBew(value, length):
     """
     Write int as big endian formatted string,
     (asserts length in [1,2,4])
     """
     return pack('>%s' % {1:'b', 2:'H', 4:'l'}[length], value)

Any of those usefull?

regards Max M





More information about the Python-list mailing list