pack a three byte int

Gabriel Genellina gagsl-py at yahoo.com.ar
Thu Nov 9 22:48:35 EST 2006


At Friday 10/11/2006 00:08, p.lavarre at ieee.org wrote:

> > > >>> import binascii
> > > >>> cdb = binascii.unhexlify('%02X%06X%02X%02X' % (0x08, 
> 0x12345, 0x80, 0))
> > > >>> binascii.hexlify(cdb)
> > >'080123458000'
> >
> > The only problem I can see is that this code is endianness-dependent;
> > the suggested versions using pack(">...") not. But this may not be of
> > concern to you.
>
>Thanks for cautioning us.  I suspect we agree:
>
>i) pack('>...') can't say three byte int.
>ii) binascii.hexlify evals bytes in the order printed.
>iii) %X prints the bytes of an int in big-endian order.
>iv) struct.unpack '>' of struct.pack '<' flips the bytes of an int
>v) struct.unpack '<' of struct.pack '>' flips the bytes of an int
>vi) [::-1] flips a string of bytes.

Yes to all.

>In practice, all my lil-endian structs live by the C/Python-struct-pack
>law requiring the byte size of a field to be a power of two, so I can
>use Python-struct-pack to express them concisely.  Only my big-endian
>structs are old enough to violate that recently (since ~1972)
>popularised convention, so only those do I construct with
>binascii.unhexlify.

So you would have no problems. I stand corrected: the code above will 
always generate big-endian numbers.


-- 
Gabriel Genellina
Softlab SRL 

__________________________________________________
Correo Yahoo!
Espacio para todos tus mensajes, antivirus y antispam ¡gratis! 
¡Abrí tu cuenta ya! - http://correo.yahoo.com.ar



More information about the Python-list mailing list