pack a three byte int
John Machin
sjmachin at lexicon.net
Thu Nov 9 20:19:40 EST 2006
p.lavarre at ieee.org wrote:
> > "struct" == "Python struct module"
> >
> > Struct module has (concise) codes B, H, I, Q for unsigned integers of
> > lengths 1, 2, 4, 8, but does *not* have a code for 3-byte integers.
>
> I thought that's what the manual meant, but I was unsure, thank you.
If it doesn't have a code for 3-byte integers in the table of codes, it
doesn't have one. What's to be unsure about??
>
> > > > 1. Not as concisely as a one-byte struct code
> >
> > Looks like you ignored the first word in the sentence ("Not").
>
> I agree I have no confident idea of what your English meant.
"Not" is rather unambiguous.
>
> I guess you're hinting at the solution you think I should find obvious,
> without volunteering what that is.
I did volunteer what it is -- try reading the message again. You may
need to use the PageDown key :-)
>
> Yes? If so, then:
No, not at all. Stop guessing. I ask again: have you read the solution
that I gave???
Here it is again:
"""
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'
>
> I guess for you "a one-byte struct code" is a 'B' provided as a "format
> character" of the fmt parameter of the struct.pack function.
>
> Yes?
Yes -- but I thought we were already over that.
> if so, then:
This does not follow.
>
> You recommend shattering the three byte int:
Yes, but not like that. See above.
>
> skip = 0x012345 ; count = 0x80
> struct.pack('>6B', 0x08, skip >> 0x10, skip >> 8, skip, count, 0)
>
> Except you know that chokes over:
>
> DeprecationWarning: 'B' format requires 0 <= number <= 255
That is not "choking" -- that is barfing; it is telling you that you
have done something silly.
>
> So actually you recommend:
>
> def lossypack(fmt, *args):
> return struct.pack(fmt, *[(arg & 0xFF) for arg in args])
> skip = 0x012345 ; count = 0x80
> lossypack('>6B', 0x08, skip >> 0x10, skip >> 8, skip, count, 0)
>
> Yes?
No, never, not in a pink fit.
>
> > > I guess you're asking me ...
> > > to show more plainly that indeed I am trying
> > > to make sense of every word of every answer
You guess wrongly.
>
> Am I helping?
No.
More information about the Python-list
mailing list