pack a three byte int

John Machin sjmachin at lexicon.net
Thu Nov 9 00:45:01 CET 2006


p.lavarre at ieee.org wrote:
> Can Python not express the idea of a three-byte int?

It is a bit hard to determine what that (rhetorical?) question means.
Possible answers:
1. Not as concisely as a one-byte struct code -- as you presumably have
already determined by reading the manual ...
2. No, but when 24-bit machines become as popular as they were in the
1960s, feel free to submit an enhancement request :-)

>
> For instance, in the working example below, can we somehow collapse the
> three calls of struct.pack into one?
>
> >>> import struct
> >>>
> >>> skip = 0x123456 ; count = 0x80
> >>>
> >>> cdb = ''
> >>> cdb += struct.pack('>B', 0x08)
> >>> cdb += struct.pack('>I', skip)[-3:]
> >>> cdb += struct.pack('>BB', count, 0)
> >>>
> >>> print ' '.join(['%02X' % ord(xx) for xx in cdb])
> 08 12 34 56 80 00
> >>>

You could try throwing the superfluous bits away before packing instead
of after:

| >>> from struct import pack
| >>> skip = 0x123456; count = 0x80
| >>> hi, lo = divmod(skip, 0x10000)
| >>> cdb = pack(">BBHBB", 0x08, hi, lo, count, 0)
| >>> ' '.join(["%02X" % ord(x) for x in cdb])
| '08 12 34 56 80 00'

but why do you want to do that to concise working code???




More information about the Python-list mailing list