Just a quick and specific question, this has stumped me for half an hour almost.
char * bytes = {0x01, 0xD8};
int value = 0;
value = bytes[0]; // result is 1 (0x0001)
value <<= 8; // result is 256 (0x0100)
value |= bytes[1]; // result is -40? (0xFFD8) How is this even happening?
The last operation is the one of interest to me, how is it turning a signed integer of 256 into -40?
edit: changed a large portion of the example code for brevity
In your case the type
charis equivalent tosigned char, which means that when you save the value0xD8in achar, it will come out as a negative number.The usual arithmetic conversions that happen during the
|=operation are value-preserving, so the negative number is preserved.To solve the problem, you can either make all your data types
unsignedwhen you have binary arithmetics. Or you can writevalue |= ((unsigned char) buffer[0])orvalue |= buffer[0] & 0xFF.