Padding length

 Posted by  Programming  Add comments  Tagged with:
Jul 122012
 

Quite a lot of modern protocols have padding requirements. One great example is Diameter. All attribute values there are aligned on 4-byte boundary. Reason behind such complication is in data structure alignment. While only benefit on x86 architecture is (usually minor) speed increase, on RISC processor it makes difference between doing some work or crashing in flames.

Most common alignment is on 4-byte boundaries. If we have something with length of 5, aligned length will be 8. However for length of 4, aligned length is also 4. Code is as simple as it gets:

public int GetPaddedLength(int len) {
    if ((len % 4) == 0) {
        return len;
    } else {
        return len + 4 - (len % 4);
    }
}

Lengths that fall into alignment by their own devices are not touched while all other get small boost. Of course that code can be a bit shorter if one is comfortable with C# ternary operator (present in almost all C-like languages):

public int GetPaddedLength(int len) {
    return ((len % 4) == 0) ? len : len + 4 - (len % 4);
}

And, if other alignment is needed, small generalization is all it takes:

public int GetPaddedLength(int len, int align) {
    return ((len % align) == 0) ? len : len + align - (len % align);
}

 Leave a Reply

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>