Search code examples
cinteger-promotion

bit representation of unsigned int a = -1


What is the bit representation of unsigned int x =-1; Can we assign unsigned int with a negative integer?

#include<stdio.h> 
int main(){
    unsigned int x = -1; 
    int y = ~0; 
    if(x == y) 
        printf("same"); 
    else
        printf("not same"); 
    return 0;
}

output :

same

and how is it possible, x being unsigned

#include<stdio.h> 

int  main()     
{

unsigned int x = -4; 
if (x == -4)
   printf("true");
else 
   printf("FALSE");
}

output:

true


Solution

  • When an unsigned int value is compared to int value, the int value is implicitly converted to unsigned int type. The result of that conversion is congruent to the original value modulo 2N, where N is the number of value-forming bits in unsigned int. This modulo equals to UINT_MAX + 1.

    For this reason initialization

    unsigned int x = -1;
    

    initializes x with some unsigned value congruent to -1 modulo UINT_MAX + 1. Incidentally, this is nothing else than UINT_MAX. This value has 1 in each value-forming bit of unsigned int object. It works that way with any unsigned type.

    Expression ~0 is evaluated in the domain of signed int type, and then y is implicitly converted to unsigned int in x == y comparison. Apparently, on your platform the conversion produces the same unsigned int value with all value-forming bits set to 1. Hence the equality.

    Initialization

    unsigned int x = -4;
    

    initializes x with some unsigned value congruent to -4 modulo UINT_MAX + 1. In comparison x == -4 the right-hand side is converted to unsigned type by the very same rules. Hence the equality.