Reputation: 17296
I am writing some code to read bitmap files.
Here is the struct I am using to read the bitmap header. See also:
https://msdn.microsoft.com/en-us/library/windows/desktop/dd183374(v=vs.85).aspx
struct BITMAPFILEHEADER
{
WORD bfType; // 2
DWORD bfSize; // 6
WORD bfReserved1; // 8
WORD bfReserved2; // 10
DWORD bfOffBits; // 14
}; // should add to 14 bytes
If I put the following code in my main function:
std::cout << "BITMAPFILEHEADER: " << sizeof(BITMAPFILEHEADER) << std::endl;
the program prints:
BITMAPFILEHEADER: 16
It appears to be re-aligning the data in the struct on 4-byte boundaries, presumably for efficiency. Of course this renders me unable to read a bitmap... Even though microsoft, and others, specifiy this is the way to do it...
How can I prevent the structure re-alignment?
Upvotes: 3
Views: 2261
Reputation: 16
To avoid this, you can obviously designate the compiling granularity. Just use this switch:
##pragma pack(1)
This tells the compiler to align to 1-byte boundaries (do nothing)
To resume normal padding (from before the previous #pragma pack
):
#pragma pack(pop)
Upvotes: 1
Reputation: 17296
The solution I found which works on gcc compilers, under linux:
struct BITMAPFILEHEADER
{
WORD bfType;
DWORD bfSize;
WORD bfReserved1;
WORD bfReserved2;
DWORD bfOffBits;
} __attribute__((packed));
There is probably a better, more cross compiler/platform way of doing things, but I don't know what it is.
Upvotes: 5