Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unsigned integer in c

Tags:

c

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.

like image 220
Angus Avatar asked Jun 27 '26 15:06

Angus


2 Answers

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.

like image 133
Femaref Avatar answered Jun 29 '26 06:06

Femaref


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.

like image 41
Ignacio Vazquez-Abrams Avatar answered Jun 29 '26 06:06

Ignacio Vazquez-Abrams