c - Calculating an integer from its Bytes gives oddly wrong results -
i'm trying read integer data file stored raw in little endian format. once got corresponding bytes calculated integer value adding numbers multiplied weight (aritmetic method below) reason value allways off 1 unit on significant byte.
other methods seem work want know why result wrong when using following code.
#include <stdio.h> #include <stdint.h> void main(){ //two bytes form 16-bit integer (little endian) char b[2] = {0xbd, 0x74}; //this gives correct answer (shift + masking) uint16_t n_correct; n_correct = (b[0] & 0xff) + ((b[1]<<8) & 0xff00); //this should give correct answer doesn't (shifting method) uint16_t n_incorrect; n_incorrect = b[0] + (b[1]<<8); //this should give correct answer doesn't (aritmetic) uint16_t n_arith; n_arith = b[0] + (b[1]*256); //this works, on little endian machines. dirty 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); }
the output is:
shifting method: 73bd == 74bd? shift + masking: 74bd == 74bd? arithmetic: 73bd == 74bd? hack: 74bd == 74bd?
as can see, using plain shifting or multiplication gives wrong answer. why?
i've done hundred times. change:
char b[2] = {0xbd, 0x74};
to
unsigned char b[2] = {0xbd, 0x74};
or, better yet
uint8_t b[2] = {0xbd, 0x74};
note char
can more 8 bits (i worked on system 32-bit char size)
Comments
Post a Comment