Search code examples
coperatorstilde

tilde operator query in C working differently


I came across this question. What is the output of this C code?

#include <stdio.h>

    int main()
    {
        unsigned int a = 10;
        a = ~a;
        printf("%d\n", a);
    }

I know what tilde operator do, now 10 can be represented as 1010 in binary, and if i bitwise not it, i get 0101, so i do not understand the output -11. Can anyone explain?


Solution

  • The bitwise negation will not result in 0101. Note that an int contains at least 16 bits. So, for 16 bits, it will generate:

     a = 0000 0000  0000 1010
    ~a = 1111 1111  1111 0101
    

    So we expect to see a large number (with 16 bits that would be 65'525), but you use %d as format specifier. This means you interpret the integer as a signed integer. Now signed integers use the two-complement representation [wiki]. This means that every integers where the highest bit is set, is negative, and furthermore that in that case the value is equal to -1-(~x), so -11. In case the specifier was %u, then the format would be an unsigned integer.

    EDIT: like @R. says, %d is only well defined for unsigned integers, if these are in the range of the signed integers as well, outside it depends on the implementation.