The short answer is padding and alignment.
> short BM;
> long size_of_file;
To ensure efficient access to size_of_file, the compiler inserts a pair of padding bytes after BM.
The common way to "fix" this is to use something like #pragma pack(1) , but there is no standard way to tell a compiler how to do this (or indeed how well your request for packing the struct will be met).
Also look up " endian-ess "
Unfortunately, the only good long-term answer (which is pretty horrible) is to read/write bytes one at a time, and assign them to the struct in the correct order.
Salem
Posting Sage
11,531 posts since Dec 2005
Reputation Points: 5,862
Solved Threads: 953
Yet another common and portable approach: use ordinar structures to create BMP info then pack them into the final char buffer (use memcpy(buffer+offset,&member,sizeof member), move offset forward and so on). Of course, it's possible to write data to a file stream directly (no need in current write pos forwarding).
Add some syntax sugar, for example:
struct bmp_header
{
short BM;
long size_of_file;
long reserve;
long offset_of_pixle_data;
long size_of_header;
long width;
long hight;
short num_of_colour_plane;
short num_of_bit_per_pix;
long compression;
long size_of_pix_data;
long h_resolution;
long v_resolution;
long num_of_colour_in_palette;
long important_colours;
void* pack(void* pbuf) {
char* p = (char*)pbuf;
int i = 0;
# define PACK(member) {memcpy(p+i,&member,sizeof member);i+=sizeof member;}
PACK(BM)
PACK(size_of_file)
...
PACK(important_colours)
# undef PACK
return pbuf;
}
}
HEADER;
...
HEADER.pack(buffer)
A nasty thing but it works ;)
ArkM
Postaholic
2,001 posts since Jul 2008
Reputation Points: 1,234
Solved Threads: 348