Search code examples
cprintingunsigned-integer

How does the compiler treats printing unsigned int as signed int?


I'm trying to figure out why the following code:

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

a will be 00001010 to begin with, and after NOT opertaion, will transform

into 11110101.

What happens exactly when one tries to print a as signed integer, that makes

the printed result to be -11?

I thought i would end up seeing -5 maybe (according to the binary representation), but not -11.

I'll be glad to get a clarification on the matter.


Solution

  • 2's complement notation is used to store negative numbers.

    The number 10 is 0000 0000 0000 0000 0000 0000 0000 1010 in 4 byte binary.

    a=~a makes the content of a as 1111 1111 1111 1111 1111 1111 1111 0101.

    This number when treated as signed int will tell the compiler to take the most significant bit as sign and rest as magnitude.

    The 1 in the msb makes the number a negative number.

    Hence 2's complement operation is performed on the remaining bits.

    Thus 111 1111 1111 1111 1111 1111 1111 0101 becomes 000 0000 0000 0000 0000 0000 0000 1011.

    This when interpreted as a decimal integer becomes -11.