Want to build a binary header block
Larry Bates
larry.bates at websafe.com
Tue May 1 09:52:03 EDT 2007
Bob Greschke wrote:
> This is the idea
>
> Block = pack("240s", "")
> Block[0:4] = pack(">H", W)
> Block[4:8] = pack(">H", X)
> Block[8:12] = pack(">B", Y)
> Block[12:16] = pack(">H", Z))
>
> but, of course, Block, a str, can't be sliced. The real use of this is a
> bit more complicated such that I can't just fill in all of the "fields"
> within Block in one giant pack(). I need to build it on the fly. For
> example the pack(">H", X) may be completely skipped some times through the
> function. There are many more fields in Block than in this example and they
> are all kinds of types not just H's and B's. What I really want is a C
> struct union. :)
>
> How would I do this?
>
> Thanks!
>
> Bob
>
>
When I have something like this I normally write a class
for it and make its __str__ method return the packed output.
Example (not tested, but you should get the drift):
import struct
class blockStruct:
def __init__(self):
self.hstring=240*" "
self.W=None
self.X=None
self.Y=None
self.Z=None
return
def __str__(self):
rtnvals=[]
rtnvals.append(struct.pack("240s", self.hstring)
rtnvals.append(struct.pack(">H", W))
.
.
.
return ''.join(rtnvals)
Then in your main program
bS=blockStruct()
bs.hstring='this is a test'.ljust(240, ' ')
bs.W=12
bs.X=17
bs.Y=1
bs.Z=0
print bS
Seemed to be a good way that made debugging and understanding
easy for me.
-Larry
More information about the Python-list
mailing list