Need elegant way to cast four bytes into a long

sismex01 at hebmex.com sismex01 at hebmex.com
Fri Aug 8 12:00:48 EDT 2003


> From: Skip Montanaro [mailto:skip at pobox.com] 
> Sent: Viernes, 08 de Agosto de 2003 10:55 a.m.
> 
>     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
>

Kinda like this?

Python 2.2.3 (#42, May 30 2003, 18:12:08) [MSC 32 bit (Intel)] on win32
Type "copyright", "credits" or "license" for more information.
IDLE 0.8 -- press F1 for help
>>> a = [ 0x11, 0x33, 0x66, 0x99 ]
>>> import struct
>>> I = struct.unpack("=i","".join([chr(i) for i in a]))[0]
>>> print I, hex(I)
-1721355503 0x99663311
>>> 

As you can see, this is subject to platform byte-ordering
gimmics, but you can force it by changing the "=" in the
format string to "<" to force little-endian and ">" for
bigger-endian.

HTH

-gustavo

pd: one little, two little, three little endians, ...


Advertencia:La informacion contenida en este mensaje es confidencial y
restringida, por lo tanto esta destinada unicamente para el uso de la
persona arriba indicada, se le notifica que esta prohibida la difusion de
este mensaje. Si ha recibido este mensaje por error, o si hay problemas en
la transmision, favor de comunicarse con el remitente. Gracias.





More information about the Python-list mailing list