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;
}
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;
}
It is better to avoid shifting negative numbers. For <<
it is undefined behavior. For >>
it is implementation defined:
The result of
E1 >> E2
isE1
right-shiftedE2
bit positions. IfE1
has an unsigned type or ifE1
has a signed type and a nonnegative value, the value of the result is the integral part of the quotient ofE1 / 2
E2
. IfE1
has a signed type and a negative value, the resulting value is implementation-defined.
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.