Search code examples
cbitmapvga

Especifying Hexadecimal values in an array in C for bitmap files


I have a simple question regarding how the header file of a bitmap is read.

I have my bitmap array like this:

typedef unsigned char byte;
char bitmap[(188*180)+1024+54];  //The image size is 188*180  +  the header file of 54 bytes+ the pallete table´s 1024 bytes

I´m specifying the values according to the bmp header, but I have a question when having a value that´s bigger than a byte. For example, my image width is 288 which is 0x120 in hexadecimal. However I cannot simply say:

 bitmap[19] = 0x120;

because that´s bigger than one byte. According to what I read I have a double word to store my image height (That is 4 bytes) so I can use bitmap[20],bitmap[21] and bitmap[22] to store the entire number.

How should I divide the number to get the same value stored on the header file? I´m not sure if the values are added or are read as a single hex number when opening the bmp file.


Solution

  • TL;DR

    The values are read as a single DWORD (32-bit) number.


    BMP file format is described in Wikipedia, as well as in numerous places on the Internet. Please note that the proper offset is 18, not 19 as you suggest in your question. So the four bytes are at offsets 18, 19, 20 and 21.

    In your code:

    typedef unsigned char byte;
    char bitmap[(188*180)+1024+54];
    

    to force the width of the image to 0x120, you can do this:

    bitmap[18] = 0x20;
    bitmap[19] = 0x01;
    bitmap[20] = 0x00;
    bitmap[21] = 0x00;
    

    Or in the general case:

    uint32_t width = ...; // 0x120 in your case, any value in general case
    bitmap[18] = width & 0xff;
    bitmap[19] = (width >> 8) & 0xff;
    bitmap[20] = (width >> 16) & 0xff;
    bitmap[21] = (width >> 24) & 0xff;
    

    Note that the least-significant bytes should be at lower addresses (little-endian order) - this is not always documented, but is always implied when talking about data structures in Windows.