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:
int negative = (input >> ((sizeof(int) * 8) - 1)) & 0x01;
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 int has on the current platform using sizeof(int) * 8. To get the highest bit via right shift, we need to shift by size - 1. As the right shift is arithmetical in C (meaning if the highest bit is 1, we fill the int with 1s from the left on), we need to kill all extra bits using logical and with 0x01 (or simply 1, whatever you prefer).
The result is an int with value 1 if the input is negative, or 0 if 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.
See if the value is less than 0x80, 0x8000, 0x80000000, or 0x8000000000000000, depending on the bit depth of the type. If it is less than then it's positive, otherwise it's negative.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With