大家都知道 BMP 文件是小端字节序的。维基百科页面说前 2 个字节必须是0x424D为了确保该文件是 BMP,但是当我从 BMP 文件获取前 2 个字节时,它给了我相反的两个字节0x4D42。
我的代码:
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");
}
Run Code Online (Sandbox Code Playgroud)
现在,BMP 文件字节如何按小端排序,并给我反转的前 2 个字节?
第一个字节是“B”(0x42),第二个字节是“M”(0x4D)
小尾数uint16_t会将其视为 0x4D42,这就是您正在读取的内容。请尝试以下方法以获得独立于字节序的解决方案。
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");
}
Run Code Online (Sandbox Code Playgroud)
顺便说一句,Wiki 说的是“ID 字段(42h,4Dh)”,而不是“前 2 个字节必须是 0x424D”。