Could someone explain me why:
x = x << 1;
x = x >> 1;
and:
x = (x << 1) >> 1;
pr
When you bitshift the result is promoted to int
. In the first example you convert int back to uint8_t everytime, and lose the intermediate data. But in the second example you keep the int result when you shift back.
This is due to integer promotions, both operands of the bit-wise shifts will be promoted to int in both cases. In the second case:
x = (x << 1) >> 1;
the result of x << 1
will be an int and therefore the shifted bit will be preserved and available to the next step as an int which will shift it back again. In the first case:
x = x << 1;
x = x >> 1;
when you assign back to x
you will lose the extra bits. From the draft C99 standard section 6.5.7 Bit-wise shift operators
it says:
The integer promotions are performed on each of the operands.
The integer promotions are covered in section 6.3.1.1
Boolean, characters, and integers paragraph 2 which says:
If an int can represent all values of the original type, the value is converted to an int; otherwise, it is converted to an unsigned int. These are called the integer promotions.48)
The last piece of this why does the conversion from the int value 256
to uint8_t give us 0
? The conversion is covered in section 6.3.1.3
Signed and unsigned integers which is under the Conversions section and says:
Otherwise, if the new type is unsigned, the value is converted by repeatedly adding or subtracting one more than the maximum value that can be represented in the new type until the value is in the range of the new type.49)
So we have 256 - (255+1)
which is 0
.