1

I am trying to create a BITMAP image using C++.

Code:

#include <stdio.h>
#include <fstream>
using namespace std;

struct BMPHeader{
    short int file_type = 0x4d42;
    int file_size = 0;
};

int main(){
    struct BMPHeader img;
    printf("%ld",sizeof(img.file_type));
    ofstream f1;
    f1.open("output.bmp", ios::out);
    f1.write(reinterpret_cast <char *> (&img), sizeof(img));
    f1.close();
    return 0;
}

Now if I use xxd to view the output.bmp file I get

$ xxd output.bmp 
00000000: 424d 0000 0000 0000                      BM......

Here the variable "file_type" becomes 4 bytes when stored. However the output of sizeof() is 2bytes.

Now, if the variable "file_size" is not declared, then it's stored as 2 bytes(which is what I want).

struct BMPHeader{
    short int file_type = 0x4d42;
    //int file_size = 0;
};
xxd output.bmp 
00000000: 424d                                     BM

What am I doing wrong here?

Kevin
  • 83
  • 4
  • 6
    Look at **padding**. – Jarod42 Sep 25 '20 at 16:25
  • The header struct probably has padding. Depending on the compiler there may be a way to pack the structure – drescherjm Sep 25 '20 at 16:26
  • Related to [struct-padding-in-c++](https://stackoverflow.com/questions/5397447/struct-padding-in-c) – Jarod42 Sep 25 '20 at 16:27
  • 2
    Print the value of `sizeof(img)` and you will see that it uses 8 bytes. You are using 4 bytes for the int, 2 bytes for the short, and 2 extra bytes are added by the compiler as padding. – darcamo Sep 25 '20 at 16:37
  • 2
    If you know you want 2 bytes, then use `int16_t` or `uint16_t`. Don't use `short` which could have different sizes on different implementations. – Jesper Juhl Sep 25 '20 at 16:54
  • Use fixed size datatypes and __attribute__((packed)). – doomista Sep 25 '20 at 17:27

0 Answers0