0

I have this simple piece of code. can anyone explain why the output is ffff not 0fff ??

#include<stdio.h>

int main(){

   printf("\n%x",(-1>>4));

   return 1;
}
Asif Ahmed
  • 93
  • 1
  • 8

2 Answers2

1

It is better to avoid shifting negative numbers. For << it is undefined behavior. For >> it is implementation defined:

The result of E1 >> E2 is E1 right-shifted E2 bit positions. If E1 has an unsigned type or if E1 has a signed type and a nonnegative value, the value of the result is the integral part of the quotient of E1 / 2E2. If E1 has a signed type and a negative value, the resulting value is implementation-defined.

AlexD
  • 32,156
  • 3
  • 71
  • 65
  • can i have a little more elaborated explanation ? – Asif Ahmed Oct 30 '16 at 12:27
  • It is not known for a negative number in the right-shift whether you want divide by 16 or roll in `0` bits at the top. – Weather Vane Oct 30 '16 at 12:29
  • @AsifAhmed Undefined and implementation-defined behaviors are explained e.g. [here](http://stackoverflow.com/q/2397984). Roughly speaking, you are supposed to check documentation for your compiler. But anyway, try to avoid shifting signed negatives. – AlexD Oct 30 '16 at 12:31
0

Right shifting fills the empty bits with the sign bit. This is, it fills them with 0 if the number is positive, and with 1 if negative.

-1 = ffff = 11111111

If you shift it to the right, the resulting number will be the same.

If you don't understand why -1 = ffff, read about two's complement, wich is the representation of signed integers used by most languages.

Erik
  • 111
  • 1
  • "_Right shifting fills the empty bits with the sign bit._" It is a typical case in practice, but not guaranteed. – AlexD Oct 30 '16 at 12:36
  • I got it now. i knew that while shifting, bits are replaced by zeros only. Didnt know that it is replaced by the sign bit value during right shift. Thank you . . @AlexD – Asif Ahmed Oct 30 '16 at 18:16