Everyone knows that BMP files are little-endian. The Wikipedia page says that the first 2 bytes must be 0x424D
to make sure that this file is BMP, but when I am getting the first 2 bytes from a BMP file, it gives me the two bytes in reverse 0x4D42
.
My code:
FILE *file;
unsigned short bmpidentifier;
if((file = fopen("c://loser.bmp", "rb")) == NULL){
perror("The problem is");
return -1;
}
fread(&bmpidentifier, sizeof(unsigned short), 1, file);
if(bmpidentifier == 0x424D){
printf("The file actually is a bmp file.\n");
} else{
printf("%X\n", bmpidentifier);
printf("The file is not a bmp file.\n");
}
Now, how are the BMP file bytes sorted as little-endian, and giving me the first 2 bytes reversed?
The first byte is 'B' (0x42), the second byte is 'M' (0x4D)
A little endian uint16_t
would see this as 0x4D42 which is what you are reading. Try the following instead for a endian independent solution.
char BM[3];
BM[2] = '\0';
if (fread(BM, 1, 2, file) && (strcmp("BM",BM)==0)) {
printf("The file actually is a bmp file.\n");
}
By the way Wiki says "ID field (42h, 4Dh)", not "first 2 bytes must be 0x424D".