Integer |= Char; operation ignoring high order byte in Integer
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 char
is equivalent to signed char
, which means that when you save the value 0xD8
in a char
, 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 unsigned
when you have binary arithmetics. Or you can write value |= ((unsigned char) buffer[0])
or value |= buffer[0] & 0xFF
.
In order to perform the |=
operation, we need the operands on both sides to be the same size. Since char
is smaller than int
, it has to be converted to an int
. But, since char
is a signed type, it's expanded to an int
by sign extension.
That is, D8
becomes FFD8
before the or operation even happens.
I think I got the problem, here char is a signed character (216) but the signed character can store the value in between (-128,127) that means 216 (11011000) Most significant bit is 1 that is this is a negative number which 2's compliment is 00101000 which is equivalent to -40
when you doing this value |= bytes[1];
in that case actually you are taking OR of 256 , -40
(256 | -40) is equal to -40
精彩评论