4

I am working with BMP file. In copy.c we have this code

 // determine padding for scanlines
int padding =  (4 - (bi.biWidth * sizeof(RGBTRIPLE)) % 4) % 4;

What is padding exactly in BMP file ? do I miss something ?

1
  • Isn't int padding = (4 - (bi.biWidth * sizeof(RGBTRIPLE)) % 4) % 4; the same as int padding = (4 - (bi.biWidth * sizeof(RGBTRIPLE)) % 4)? Nov 23 '19 at 10:55
3

I think the answer is here:

To speed up mathematical operations with bitmaps, these scanlines must be divisible by 4 (4, 8, 12... 40... etc). Why? Because it is way faster to multiply a number with 4 than say 3. It has to do with bit-shifting, but I'm not going to explain that here.

1

The number of bytes in a scanline of the 24-bit BMPs in this pset must be a multiple of 4. See the quote below from the pset specs:

Each scanline in small.bmp thus takes up (3 pixels) × (3 bytes per pixel) = 9 bytes, which is not a multiple of 4. And so the scanline is "padded" with as many zeroes as it takes to extend the scanline’s length to a multiple of 4. In other words, between 0 and 3 bytes of padding are needed for each scanline in a 24-bit BMP. (Understand why?)

Padding is a crucial component of this pset, so I suggest re-reading the specs to make sure you fully understand how padding works.

5
  • but why is it must be multiple of 4?
    – Yu Xiao
    Apr 13 '16 at 14:23
  • Same question why is it must be multiple of 4?
    – Assarin
    Oct 17 '17 at 5:34
  • But why 4 not 52114343434?! Nov 24 '18 at 17:16
  • this is such a bad answer you just reiterate the question ? Aug 10 '19 at 19:24
  • Quote from the link: The reason you read/write data in/out from RAM and the CPU 4-bytes at a time, is because this is the current native word length of the processor-- 32 bits. aka "unsigned long".
    – Pioneer
    Sep 10 '19 at 20:09
0

The BMP color table has four bytes in each color table entry. The bytes are for the blue, green, and red color values. The fourth byte is padding and is always zero. For a 256 gray shade image, the color table is 4x256 bytes long. The blue, green, and red values equal one another. The final part of the BMP file is the image data. The data is stored row by row with padding on the end of each row. The padding ensures the image rows are multiples of four. The four, just like in the color table, makes it easier to read blocks and keep track of addresses.

Find more information here please:

https://homepages.inf.ed.ac.uk/rbf/BOOKS/PHILLIPS/cips2ed.pdf

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .