0

I've read both in Wikipedia and in a few answers here on stack overflow regarding processor alignment, but there's one thing I don't understand:

If a 32 bit processor aligns to 4 byte increments, why would struct.pack('BH', 1, 2) add a null byte in the middle?

The short will not border on an address divisible by 4 (only divisible by 2), and when the processor will read a word, it will read all 4 bytes either case, whether the short is in the middle or at the end.

It does not prepare the ground for more data either as another byte can join in address 3-4 and take no extra space, while being perfectly 1-byte aligned.

Bharel
  • 23,672
  • 5
  • 40
  • 80

1 Answers1

0

By default struct uses the conventions that the platform C compiler is using. You can tell struct to use no padding

See this for an explanation of the usual alignment.

Storage for the basic C datatypes on an x86 or ARM processor doesn’t normally start at arbitrary byte addresses in memory. Rather, each type except char has an alignment requirement; chars can start on any byte address, but 2-byte shorts must start on an even address, 4-byte ints or floats must start on an address divisible by 4, and 8-byte longs or doubles must start on an address divisible by 8. Signed or unsigned makes no difference.

Mihai Andrei
  • 1,024
  • 8
  • 11