This algorithm finds the offset from the previous field to the start of the next field in a C struct. It worked when tested (part of the Laddie C struct translation). I put this up because there doesnt seem to be one posted. Feel free to use, modify, etc.
Input:
int size; // field size
int prev_size; // size of previous field
int total_size; // total used (fields + padding) size so far
int BLOCK_SIZE; // aka word size, usually 4 (32 bits)
ALGORITHM
int pad = 0;
// it starts on a new block
if (total_size%BLOCK_SIZE == 0) {
// nothing
}
// it fits in the last block with the previous one
else if (size + (BLOCK_SIZE - (total_size%BLOCK_SIZE)) <= BLOCK_SIZE
&& prev_size <= BLOCK_SIZE) {
// nothing
}
// it doesnt fit in the last block with company
else {
pad = BLOCK_SIZE - (total_size%BLOCK_SIZE);
prev_size += pad;
}
output << offset is prev_size
// set up for the next one
total_size += size + pad
prev_size = size