我正在编写一个 C 程序来读取和解析 BMP header 。前 2 个字符是字符,我打印得很好。但是,所有其他位都是小端格式的整数,因此我将它们向后存储。在十六进制中,我得到了正确的答案。但是,当我尝试将它们转换为 int(为了便于阅读)时,我得到了一个无效数字。
bmp.c--
printf("file size: "%02x %02x %02x %02x\n", bmp->size[0], bmp->size[1], bmp->size[2], bmp->size[3]);
printf("file size: "%d\n", bit2int(bmp->size));
bit2int函数--
int bit2int(void *thing)
{
return *(int*)thing;
}
输出--(实际文件大小为415,798字节)
file size: 00 06 58 36
file size: 911738368
编辑 1 -- 我目前正在使用的功能
void storebackwards(void *dst, void *src, int offset, int n) {
for(int i = n; i > 0; i--)
memcpy( dst + n - i, src + offset + i - 1, 1);
}
最佳答案
我喜欢 user1063935 的解决方案,但会使用移位运算符
int bit2int(unsigned char *thing)
{
return thing[3] + thing[2] << 8 + thing[1] << 16 + thing[0] << 24;
}
关于c - 如何将 4 位字符数组转换为 Int?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49458664/