我正在尝试从以小端格式原始存储的数据文件中读取整数。一旦我得到相应的字节,我最初通过将数字乘以它们的权重(下面的算术方法)来计算整数值,但由于某种原因,该值总是在最高有效字节上偏离一个单位。
其他方法似乎有效,但我想知道为什么使用以下代码时结果是错误的。
#include <stdio.h>
#include <stdint.h>
void main(){
//Two bytes that form a 16-bit integer (Little endian)
char b[2] = {0xBD, 0x74};
//This gives a correct answer (Shift + Extra masking)
uint16_t n_correct;
n_correct = (b[0] & 0xFF) + ((b[1]<<8) & 0xFF00);
//This should give a correct answer but doesn't (Shifting method)
uint16_t n_incorrect;
n_incorrect = b[0] + (b[1]<<8);
//This should also give a correct answer but doesn't (Aritmetic)
uint16_t n_arith;
n_arith = b[0] + (b[1]*256);
//This works, on little endian machines. Dirty but works. (Hack)
uint16_t n_hack;
uint8_t* n_ptr = (uint8_t*)&n_hack;
n_ptr[0] = b[0];
n_ptr[1] = b[1];
printf("Shifting method: %X == %X%X?\n", n_incorrect, b[1]&0xFF, b[0]&0xFF);
printf("Shift + Masking: %X == %X%X?\n", n_correct, b[1]&0xFF, b[0]&0xFF);
printf(" Arithmetic: %X == %X%X?\n", n_arith, b[1]&0xFF, b[0]&0xFF);
printf(" Hack: %X == %X%X?\n", n_hack, b[1]&0xFF, b[0]&0xFF);
}
输出是:
Shifting method: 73BD == 74BD?
Shift + Masking: 74BD == 74BD?
Arithmetic: 73BD == 74BD?
Hack: 74BD == 74BD?
如您所见,使用简单的移位或乘法会给出错误的答案。为什么?