Need elegant way to cast four bytes into a long

John Machin sjmachin at lexicon.net
Fri Aug 8 18:07:34 EDT 2003


Skip Montanaro <skip at pobox.com> wrote in message news:<mailman.1060358114.21520.python-list at python.org>...
> wsh> I have been getting what I want in this sort of manner :
> 
>     wsh>        l  = 0L

The above line is redundant.

>     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)
> 
Bzzzzzt. Oh the joys of operator precedence! 

Python 2.2.3 (#42, May 30 2003, 18:12:08) [MSC 32 bit (Intel)] on win32
>>> a = range(0x11,0x55,0x11)
>>> hex(a[0] + a[1] << 8 + a[2] << 16 + a[3] << 24)
'0x0'
>>> hex(a[0] + (a[1] << 8) + (a[2] << 16) + (a[3] << 24))
'0x44332211'
>>> hex(a[0] | a[1] << 8 | a[2] << 16 | a[3] << 24)
'0x44332211'

See http://www.python.org/doc/current/ref/summary.html




More information about the Python-list mailing list