4

I am trying to pack a string and the length of a string.

fmt = '<P' + str(len(string)) + 'p'

This leads me to an error : struct.error: bad char in struct format Whereas, doing

fmt = 'P' + str(len(string))+'p'

Does not give me an error. I am unable to understand why this happens, my understanding is that specifying '<' at the start will make it little endian regardless of the native machine.

Warren Weckesser
  • 110,654
  • 19
  • 194
  • 214

2 Answers2

1

From the struct module docstring:

The remaining chars indicate types of args and must match exactly;
...
Special case (only available in native format):
  P:an integer type that is wide enough to hold a pointer.

So you can't modify the endianess when you use the P format; it is only available in native format.

See also Note 5 here: https://docs.python.org/2/library/struct.html#format-characters

Warren Weckesser
  • 110,654
  • 19
  • 194
  • 214
  • Missed this in the docs :(. I guess I will use long long instead of a Pointer, I just wanted a large unsigned integer to specify my length of string. –  Oct 06 '15 at 02:59
1

"<" does pack the data as little endian, but it does so by using the "Standard" alignment, not the machine's native rules of the computer. You can see the table at the struct module documentation.

As pointed out by Warren Weckesser, the P format can't have its endianess modified, but if you use "<i" instead, for example, that will completely work.