Need elegant way to cast four bytes into a long
Anton Vredegoor
anton at vredegoor.doge.nl
Mon Aug 11 04:30:23 EDT 2003
"William S. Huizinga" <wiiliam.huizinga at smiths-aerospace.com> 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?
Just for completeness, it's also possible to go back to basic style
programming.
Anton
from string import hexdigits
def hexchr(i): return hexdigits[i/16]+hexdigits[i%16]
asc = dict([(chr(i), hexchr(i)) for i in range(256)])
def tolong(s): return long(''.join(map(asc.get,s[::-1])),16)
def test():
a = '\x01\x02\x03\x04'
print tolong(a)
if __name__=='__main__':
test()
More information about the Python-list
mailing list