Reputation: 197
I found this source which works quite well, I just want to ask about this piece of code which I dont get:
//calculate total size of RGBQUAD scanlines (DWORD aligned)
bih.biSizeImage = (((bih.biWidth * 3) + 3) & 0xFFFC) * bih.biHeight ;
I get why there is "*3", but dont get the "+3" and the bitwise AND with FFFC hexa. Could someone explain me why he claculates size of the image this way?
Thanks
Upvotes: 3
Views: 1147
Reputation: 12817
If you try that out for various values, you'll see it's actually forcing (width * 3) to round up to the smallest multiple of 4 that will contain it. He's probably doing this to enforce things to be 32-bit aligned.
Using python:
>>> f = lambda x: ((x * 3) + 3) & 0xFFFC
>>> [f(x) for x in range(1, 20)]
[4, 8, 12, 12, 16, 20, 24, 24, 28, 32, 36, 36, 40, 44, 48, 48, 52, 56, 60]
The following shows the difference between just doing the straight multiplication and rounding upwards towards a multiple of 4
>>> [(3*x, f(x)) for x in range(1, 8)]
[(3, 4), (6, 8), (9, 12), (12, 12), (15, 16), (18, 20), (21, 24)]
I'm surprised the code doesn't actually document this fact. Bit twiddling is a wonderful thing, but it can seem very arbitrary.
Upvotes: 1