Explanation of the formula for padding

This is the formula given for padding in PSET5 from WEEK7 :

``````int padding =  (4 - (bi.biWidth * sizeof(RGBTRIPLE)) % 4) % 4;
``````

I don't understand what the outermost `%4` is meant for. It seems redundant to me. Someone please explain the function of this outermost `%4`.

When `bi.Width * sizeof(RGBTRIPLE)` is a multiple of 4, the expression

``````(bi.biWidth * sizeof(RGBTRIPLE)) % 4
``````

gets evaluated to 0 which, it turn, gets the expression

``````4 - [(bi.biWidth * sizeof(RGBTRIPLE)) % 4]
``````

evaluated to 4. And since you don't wanna add/seek 4 bytes in case the scanline is already a multiple of 4, you take the remainder of dividing by 4 to get it equal to 0.

``````(4 - ((bi.biWidth * sizeof(RGBTRIPLE)) % 4) % 4)
``````
• hi, i want to ask. i still don't get why we should use this formula, can't we just use this: bi.biWidth % 4 ? Mar 12 '16 at 10:55
• @PatrickBenzImanuel no, because `biWidth` is the width of the BMP in pixels, not in bytes. I made a small edit, wanna re-read the answer? let me know if you still don't get it!
– kzidane
Mar 12 '16 at 11:01
• So I wonder why bother having four subtract it and modulo again, won't that always be the same thing? Say bi.biWidth is 3. You end up having 9 % 4, which is 1. Then 4 - 1 is 3. 3 % 4 is then 1 again. Nov 17 '17 at 4:09
• I still think "(bi.biWidth * sizeof(RGBTRIPLE)) % 4" alone is sufficient, since when "(bi.biWidth * sizeof(RGBTRIPLE)) % 4" gets evaluate to 0, "(4 - ((bi.biWidth * sizeof(RGBTRIPLE)) % 4) % 4)" gets evaluate to 0 either. Feb 15 '18 at 21:44
• @Xichu `(bi.biWidth * sizeof(RGBTRIPLE)) % 4`, let's call that expression (1), does not calculate how many bytes we need to get to the next multiple of 4. It calculates the complementary number of bytes to that, so we need to subtract that from 4, let's call that expression (2). And since (1) itself can be 0, we have to calculate (2) % 4 to avoid ending up with 4 as a result.
– kzidane
Feb 25 '18 at 16:37

Let's say that the biWidth is 4. As such, the padding must be 0. Let's say we don't use that last %4

``````padding = (4 - (bi.biWidth * sizeof(RGBTRIPLE)) % 4);
padding = (4 - (4 * 3) % 4)
padding = (4 - (12%4)
padding = 4 - 0  = 4  !!
``````

You need that last `%4` to handle the case where the pixel width is a multiple of 4.

Here's how I wrapped my head around this formula:

(bi.biWidth * sizeof(RGBTRIPLE) finds how many bytes each scanline is

(bi.biWidth * sizeof(RGBTRIPLE)) % 4) finds the difference between the closest multiple of 4 and how many bytes each scanline is

(4 - (bi.biWidth * sizeof(RGBTRIPLE)) % 4) finds how much padding is needed unless none is needed (in which case 4 will be returned)

(4 - (bi.biWidth * sizeof(RGBTRIPLE)) % 4) % 4 makes the padding needed 0 instead of 4 if padding is not needed