[Tutor] how to struct.pack a unicode string?
eryksun
eryksun at gmail.com
Sat Dec 1 03:02:32 CET 2012
A clarification: in the default mode ('@'), struct uses native
alignment padding, but not if you override this with <, >, =, or !, as
you did.
>> fmt = endianness + str(len(hello)) + "s"
>
> That's the wrong length. Use the length of the encoded string.
Generally, however, you'd use a fixed size set by the struct
definition. For example:
typedef struct _point {
unsigned int x;
unsigned int y;
char label[8];
} point;
Python:
>>> struct.pack('II8s', *[1, 2, b'12345678This is ignored'])
b'\x01\x00\x00\x00\x02\x00\x00\x0012345678'
Null termination may or may not be required. Python will pad out the
rest of the string with nulls if it's less than the specified length:
>>> struct.pack('II8s', *[1, 2, b'1234'])
b'\x01\x00\x00\x00\x02\x00\x00\x001234\x00\x00\x00\x00'
More information about the Tutor
mailing list