Computing padding required for n-byte alignment

Viewed 6156

Say I have a collection of data (eg: strings) that must be stored in a binary file padded so that each string is, say, 4-byte aligned.

So if I have a string of length 11, it would get padded to 12 (with null bytes).
If I have a string of length 24, then no padding is necessary.
If my string has a length of 6, it would get padded to 8 bytes.

How do I compute the amount of padding required in a single expression?

I tried 4 - (string_length % 4) but it fails when my string length is a multiple of 4.

3 Answers
Related