How are signed and unsigned integers stored in c?

I am trying to run the following code, but am confused by what is going on here:

int main()
{
 /* 
    a = -1; 
    b = 0xffffffff; 
 */
if(-1 == 0xffffffff )
        printf("-1 is equal to maximum\n");
else
        printf(" -1 is not equal to maximum\n");

if(0xff < -1)
        printf(" Less than -1 \n");
if(0xff < 0xffffffff)
        printf(" Less than maximum\n");

I also tried with a comment and replaced -1 with "a" and 0xffffffff with "b", but the result is the same.

This is a 32-bit system, so I took an integer size of 4 bytes.

My way out:

-1 is equal to maximum
 Less than maximum

If -1 is equal to the maximum, then it must execute both of the last two if statements. But this does not happen. Why?

+5
source share
4 answers

I will quote this from C ++; I think the same for C:

Literal -1always signed int.

A literal 0xffis signed int, but 0xffffffffis unsigned int.

When comparing mixed characters, both operands are converted to unsigned, explaining all your results.

(.. ) ++ 11, 6:

  • int, long int long long int, , .

  • int, unsigned int, long int, unsigned long int, long long int, unsigned long long int, , .

:

  • unsigned int, 0xffffffff.

  • , 255, -1.

  • unsigned int.


, . - int, , , 0xffffffff int, unsigned int.

+5

0xffffffff -1, int , -1 0xffffffff (-1 == (~1) + 1). , -1 0xffffffff - .

0x000000ff 255, , -1, if .

, :

char c = 0xff;
if( c == -1 ) {
     printf("char 0xff is -1");
}

a char int, 8- char. char , ( ) , -1 (int).

, / .

0

-, , , , .

unsigned -1 . -1 == 0xffffffff. -1 .

0xff < -1 , int: 255 -1 .

, -1 unsigned , 0xffffffff int (, , ). unsigned int ( , , 16- ). unsigned int int, C int unsigned. ( , -1 - ), , . .

0

C/++ 2- , (MSB) .

MSB 1 -ve MSB 0 + ve. 1xxxxxxxxxx -ve number 0xxxxxxxxxx + ve. 1xxxxxxx "xxxxxx" - 2 . 0xxxxxx "xxxxx" .

-ve, MSB ( ) 1 , .

, 2 :

2 ( ), 1.

decimal 1 = 00000001

~ decimal 1 = 11111110

2 1 = 11111111 (F hex)

-1 = (1) 111111111111111

(1) - this is an MSB with the number -ve, the rest is 2 compliments of the number.

this way -1 = 0xFFFFFFFF

You can try to print the binary representation of some -ve numbers and compare 2 compliments of the binary representation of the number.

0
source

All Articles