Reputation: 21
I want to copy a 1bit BMP image and I wrote this code. I don't know why the size of Header struct in my code is 56, although it need to be 54.
My code for struct HeaderBMP:
short _type; // file type
short _size;
int _reserved;
int _offset;
int _info_size;
int _width;
int _height;
short _planes;
short _bpp;
int _compression;
int _imagesize;
int _xresolution;
int _yresolution;
int _colours;
int _impcolours;
I can't reach to size 54, it is just 52 or 56 when I try to fix . I hope you can help me to fix this.
Upvotes: 0
Views: 207
Reputation: 21
Thank you for your solution, however its is also 56 when I compile by passing argument through cmd on window 10 x64. It is 54 when it works on ubuntu and codeblock on window with passing argument in code. My solution :
typedef struct { // Total: 54 bytes
char _type[2]; // Magic identifier: 0x4d42
char _size[4]; // File size in bytes
char _reserved1[2]; // Not used
char _reserved2[2]; // Not used
char _offset[4]; // Offset to image data in bytes from beginning of file (54 bytes)
char _dib_header_size[4]; // DIB Header size in bytes (40 bytes)
char _width[4]; // Width of the image
char _height[4]; // Height of image
char _planes[2]; // Number of color planes
char _bpp[2]; // Bits per pixel
char _compression[4]; // Compression type
char _image_size[4]; // Image size in bytes
char _x_resolution_ppm[4]; // Pixels per meter
char _y_resolution_ppm[4]; // Pixels per meter
char _num_colors[4]; // Number of colors
char _important_colors[4]; // Important colors
} header;
and when I need to take value , I will do :
*(int*) header._width
I test and it works with above three cases .
Upvotes: 0
Reputation: 67476
Use fixed size integers for this kind of structs. Those types are defined in the stdint.h
header file. struct might require packing (which is implementation defined)
gcc example:
typedef struct { // Total: 54 bytes
uint16_t type; // Magic identifier: 0x4d42
uint32_t size; // File size in bytes
uint16_t reserved1; // Not used
uint16_t reserved2; // Not used
uint32_t offset; // Offset to image data in bytes from beginning of file (54 bytes)
uint32_t dib_header_size; // DIB Header size in bytes (40 bytes)
int32_t width_px; // Width of the image
int32_t height_px; // Height of image
uint16_t num_planes; // Number of color planes
uint16_t bits_per_pixel; // Bits per pixel
uint32_t compression; // Compression type
uint32_t image_size_bytes; // Image size in bytes
int32_t x_resolution_ppm; // Pixels per meter
int32_t y_resolution_ppm; // Pixels per meter
uint32_t num_colors; // Number of colors
uint32_t important_colors; // Important colors
} __attribute__((packed)) BMPHeader;
Upvotes: 2