Need elegant way to cast four bytes into a long

Bengt Richter bokr at oz.net
Fri Aug 8 21:23:00 CEST 2003


On Fri, 8 Aug 2003 10:54:38 -0500, Skip Montanaro <skip at pobox.com> wrote:

>
>    wsh> I have been getting what I want in this sort of manner :
>
>    wsh>        l  = 0L
>    wsh>        l  = a[0]
>    wsh>        l += a[1] <<  8
>    wsh>        l += a[2] << 16
>    wsh>        l += a[3] << 24
>
>    wsh> but I think that's too wordy.  Is there a more intrinsic and
>    wsh> elegant way to do this?
>
>You mean like this:
>
>    l = long(a[0] + a[1] << 8 + a[2] << 16 + a[3] << 24)
>
>You can use struct.unpack as well, though I'd be hard-pressed to get the
>details correct.  You'd be better off with "pydoc struct".
>
>Skip
>
This won't be fast, but you get to play with 2.3 ;-)

 >>> a = '\x01\x02\x03\x04'
 >>> sum([ord(c)<<8*i for i,c in enumerate(a)])
 67305985
 >>> hex(sum([ord(c)<<8*i for i,c in enumerate(a)]))
 '0x4030201'

or big-endian:

 >>> a = '\x01\x02\x03\x04'
 >>> sum([ord(c)<<8*i for i,c in enumerate( a[::-1])])
 16909060
 >>> hex(sum([ord(c)<<8*i for i,c in enumerate( a[::-1])]))
 '0x1020304'


Regards,
Bengt Richter




More information about the Python-list mailing list