JustKernel
Ray Of Hope
Structure Padding
Today I learnt a new thing regarding padding. I was programming for Octeon board and using MIPS 64 bit compiler.
I was reading the content from the file in the following order
uint32 a;
uint32 b;
uint 16 c;
uin8 d;
fscanf(“%lu, %lu, %u,%c”, &a, &b, &c, &d)
file content (10,20,30,40);
But to my surprise, values read for a and b were correct, rest all the values were incorrect. After doing R&D I found that berfore the start of new variable of new size, the previous variables should be 64 bit aligned.
for eg.. before reading c which is of size 16, ‘a’ and ‘b’ which are of size 32 should be 64 bit aligned.. Similarly, before reading ‘d’ which is of size 8, ‘c’ should be aligned to 64 bit boundary.
Thus now the fscanf goes like this.
fscanf(“%lu%lu%u%u%lu%lu%lu”, &a, &b, &c,&pad1_16bit, &pad2_32bit, &pad3_32bit, &pad4_32bit);
sizeof (a) + sizeof(b) — 64 — 64 bit aligned
sizeof (c) +sizeof(pad1_16_bit) + sizeof(pad2_32bit) – 64 bit aligned
sizeof (pad3_32bit) + sizeof(pad4_32bit) = 64 bit aligned.
Content of file
10 20 30 0 40 0
Now everything is 64 bit aligned.
Now you may be wondering where is value of variable d (which is 8 bit wide).
Aligning 8 bit variable to 64 bit boundary is a difficult task. So I read the value of 40 (from file ) in a 32 bit variable pad3_32bit..
Now 8 bit value can be extracted from pad3_32 bit as
d = (uint 8) (pad3_32bit) – For BIG ENDIAN SYSTEM
d = (uint8) (pad3_32bit <<24) for LITTLE ENDIAN SYSTEM.
A Brief about 64 bit alignment when reading from file
Anshul Makkar
Originally Posted On: 2010-03-31 01:24:47
Tags: Structure Padding
Leave a Reply