Search code examples
cintunsignednegative-number

Storing negative int value in an unsigned bit and subtracting from it


First of all I've been searching for the outcome of a negative input in an unsigned int but can't find out how it is converted. Like for example -3. How does -3 look like and how did it turn out like that?

How about subtracting from it?

What will happen?

#include <stdio.h> 

int main(){ 
unsigned int num1 = 3, num2 = -2; 

printf("num1's initial value is %u.\n",num1); 
printf("num2's initial value is %u.\n",num2); 

num1 = num1 + 1; 
num2 = num2 - 1; 

printf("num1's value is now %u.\n",num1); 
printf("num2's value is now %u.\n",num2); 

num1 = 2147483647; 
num2 = -2147483648; 

printf("num1's value is now %u.\n",num1); 
printf("num2's value is now %u.\n",num2); 

num1 = num1 + 1; 
num2 = num2 - 1; 

printf("num1's value is now %u.\n",num1); 
printf("num2's value is now %u.\n",num2);

return 0;
}

Solution

  • Okay, Let's go line by line..

    1 . unsigned int num1 = 3, num2 = -2;

    for num2 = -2 ; It will show as a positive integer of value of max unsigned integer - 1 (value depends on computer architecture and compiler).

    like if you assign num2 = X (say) and the stored value will be MAX_UNSIGNED_VALUE - (X-1).

    Basically It will assign the bit pattern representing -X (in 2's complement) to the unsigned int. Which will be a large unsigned value. For 32 bit ints this will be 2^32 - (X+1).

    Next the line

    num2 = -2147483648;
    

    So I'm considering 32 bit int it will store the (max value of an unsigned int - 2147483647). that is

    num2 = (4294967295-2147483647) = 2147483648

    Very detailed explanation about how this conversion happens is given, in the following articles.

    Hope this helps!