Given a program like below how to identify that whether the signed integer will go to a -ve or +value.
int main()
{
int a=0xDEADBEEF;
printf("%d",a);
return 0;
}
This outputs in -ve.But is there any easy way to identify it quickly without executing in visual studio.
With some bitwise magic:
To explain it:
In C, negative numbers are two’s-complement, where the highest bit denotes the sign. We first determine how many bits an
inthas on the current platform usingsizeof(int) * 8. To get the highest bit via right shift, we need to shift bysize - 1. As the right shift is arithmetical in C (meaning if the highest bit is1, we fill the int with1s from the left on), we need to kill all extra bits using logical and with0x01(or simply1, whatever you prefer).The result is an
intwith value1if the input is negative, or0if it is positive.If you want to do it on paper, take the highbyte (in your case,
DE), write out the upper half (D) and check wether the highbit of that is a zero or one.