Calculating byte alignment using a single or double modulus

Viewed 58

I apologize if this may seem obvious to some people, but I'm having a bit of a brain fart.

Can someone confirm if these two different methods of aligning to a 4 byte boundary are mathematically equivalent?

Using a single modulus operation:

int remainderLength = bytes.Length % AlignmentBoundary;
if (remainderLength > 0)
{
    int paddingLength = AlignmentBoundary - remainderLength;
    for (int i = 0; i < paddingLength; i++)
        bytes.Add(0);
}

Using a double modulus operation:

int paddingLength = (AlignmentBoundary - bytes.Length % AlignmentBoundary) % AlignmentBoundary;
for (int i = 0; i < paddingLength; i++)
    bytes.Add(0);
1 Answers

Yes, they are mathematically equivalent.

In the second option the second modulo helps you fix the result in the cases which the first modulo is 0.

Related