I am doing the following bitwise shift in Microsoft C++:
uint8_t arr[3] = {255, 255, 255};
uint8_t value = (arr[1] << 4) >> 4;
The result of these operations confused me quite a bit:
value = 255
However, if I do the bitwise shift separately:
value = (arr[i] << 4);
value = value >> 4;
the answer is different and makes much sense:
value = 15
Can someone explain to me why this happens? I am familiar with the concepts of bitwise shift, or so I believed...
Thanks in advance!
(P.S.: It seems g++
will have the same behavior. I am probably missing some important concepts with bitwise shift. Any help is greatly appreciated!)
Expression (arr[1] << 4)
will implicitly promote the value of arr[1]
to type unsigned int
before applying the shift operation, such that the "intermediate" result will not "loose" any bits (cf, for example, the explanation in implicit conversions).
However, when you write value = (arr[i] << 4);
, then this "intermediate" result will be converted back to uint_8
, and in this step bits get cut off.
See the difference when you write uint8_t value = ((uint8_t)(arr[1] << 4)) >> 4;