-1

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;
}   
AppY
  • 1
  • 1
  • 4
    Are you sure you recompiled after you changed it from left shift to right shift? – Patrick Maupin Aug 01 '15 at 19:57
  • Change the printf to `printf("hello %d\n", y);` and try again. – user3386109 Aug 01 '15 at 20:02
  • 1
    Right shifting negative numbers is *implementation defined*. On the systems using the common 2's complement representation, it's equivalent to arithmetic shift and your program will print `-1`. If it's really printing `-8`, you should update the Q with your system details. – P.P Aug 01 '15 at 20:10
  • Thankyou all ; I had forgotten to convert 2's complement back to decimal. – AppY Aug 01 '15 at 20:39

2 Answers2

2

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.

0

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

Shift operator in C

Hope it helps.Thanks.

Community
  • 1
  • 1