0

While solving problems, I stuck here thinking how the output of this program gives ffffffff. Since the left shift of bits should give -2. I cross-checked here Online Calculator giving -2. I can see the binary value of -1 is 11111111. But how? Also, my observance from here Signed int conversion:

-1 ---> 0xff --> 1111 1111

-2 ---> 0xfe --> 1111 1110

-3 ---> 0xfd --> 1111 1101

-8 ---> 0xf8 --> 1111 1000

#include<stdio.h>
int main()
{
   printf("%x", -1<<1);
   getchar();
   return 0;
}  

Please tell me how the compiler looks integers below 0 when bitwise shift operators are used?

Community
  • 1
  • 1
Dr. Essen
  • 603
  • 2
  • 9
  • 25
  • 2
    Are you asking why -1 is 11111111 and -2 is 11111110 in binary? The compiler just shifts the bits to the left, no magic there. How you interpret the bits depends on your system, but it is most likely *two's complement*. Google that. – DeiDei Feb 07 '18 at 06:25
  • 1
    The bahavior is undefined: "The result of E1 << E2 is ......... If E1 has a **signed type and nonnegative value**, and E1×2E2 is representable in the result type, then that is the resulting value; **otherwise, the behavior is undefined.**" – Support Ukraine Feb 07 '18 at 06:34
  • For me it's prints fffffffe -->-2 not ffffffff. – ntshetty Feb 07 '18 at 06:35
  • Sorry for the duplicate question. I couldn't find the similar one. – Dr. Essen Feb 07 '18 at 06:49

1 Answers1

1

When I run your program, it outputs “fffffffe”. However, the behavior is undefined. The C standard says that a left shift is defined only if the value being shifted is non-negative (and then only if the shift does not overflow). So, when you evaluate -1 << 1, a C implementation is allowed to do anything.

Eric Postpischil
  • 195,579
  • 13
  • 168
  • 312