The output to this Leftshift assignment operator is -8.I didn't understand how.Please help!
#include < stdio.h>
int main()
{
int y = -1;
y <<= 3;
printf("%d", y);// prints -8;
return 0;
}
The output to this Leftshift assignment operator is -8.I didn't understand how.Please help!
#include < stdio.h>
int main()
{
int y = -1;
y <<= 3;
printf("%d", y);// prints -8;
return 0;
}
In a 32-bit 2's-complement signed integer, the hexadecimal and binary representations of these numbers are:
-1 = 0xffffffff = 11111111 11111111 11111111 11111111
-8 = 0xfffffff8 = 11111111 11111111 11111111 11111000
The second of which is clearly the first left-shifted by three bits, with the three extra 1s "falling off" the left side, and the three bits on the right being filled with zeroes.
Valid question. The answer lies in shift-wise operators behaves differently for negative values. Especially for leftshift assignments.
You can go through these 2 links to clear your doubts.
Bitwise operation on signed integer
and
Hope it helps.Thanks.