Depiction of binary digit changes during promotion from signed to unsigned integers/what happens?

95 Views Asked by At

y is promoted to unsigned int and compared with x here.Does binary number comparison happen everytime? Then if(12 == -4) is done, why can't it promote LHS to unsigned and print "same"?(considering 12 = 1100, -4 = 1100)Please correct if I am wrong.

#include<stdio.h>
int main() 
{
    unsigned int x = -1;
    int y = ~0;
    if(x == y)//1.what happens if( y == x) is given?.O/P is "same" then also.
        printf("same");//output is "same"
    else
        printf("not same");
    printf("%d",x);//2.output is -1.Won't x lose it's sign when unsigned is given?My hunch is x should become +1 here. 
    getchar();
    return 0;
}

Please also provide the binary number working for the above code and answers to 1. and 2. in the code comments.Thank you.

2

There are 2 best solutions below

0
On

An unsigned int =-1 should actually interpreted as the max unsigned int(4294967295); surely is not transformed into 1.

0
On

First check in your system for size of unsigned int.

in my machine: printf("%zu\n",sizeof(unsigned int));//4 byte

as we have 4 bytes to store an Uint data type, we can say

unsigned int x ;//

x:Range[0, Max_number_with_4byte]

Max_number_with_4byte: (2^32) - 1 = 0xFFFFFFFF

obviously x can hold only positive numbers because of unsigned.

but you give to x = -1;, suppose a circular behaviour, when we put back one step from 0, x reach to last point: Max_number_with_4byte.

and printing x to screen shows: 0xFFFFFFFF

see hex equivalent of x with printf("%x\n",(unsigned int )x); and printf("%y\n",(unsigned int )y); to see equality of x,y.

consider y = ~0; we have 32 bits for y if ~ operator use in y all bits are changes to 1, in hex form we see FFFFFFFF. (we cant print binary numbers with printf and use equal hex representation)

you can see this online calculator how to convert -1 to 0xFFFFFFFF

Answer to your Question

y is not promoted to unsigned int. it is just changes its bits form 0 -> 1

Does binary number comparison happen every time?

Yes in every conditions for example in if(10 > 20) first both 10 and 20 converted to its correspondent binary numbers then compare.

if (12 == -4) see my above explanation.

-4 not equals to 1100 inside computer (your variable).

-4 = 0xFFFFFFFC see