リトル エンディアン形式で生のまま保存されているデータ ファイルから整数を読み取ろうとしています。対応するバイトを取得したら、最初は重みを掛けた数値を加算して整数値を計算しました(以下の算術法)が、何らかの理由で、値は常に最上位バイトで1単位ずれています。
他の方法は機能しているようですが、次のコードを使用すると結果が間違っている理由を知りたいです。
#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?
ご覧のとおり、単純なシフトまたは乗算を使用すると、間違った答えが得られます。なぜ?