Search code examples
cbit-manipulationcode-snippets

Why is the output -33 for this code snippet


#include<stdio.h>

int main()
{
    int a=32;
    printf("%d\n", ~a);  //line 2
    return 0;
}

o/p = -33

Actually in the original snippet line 2 was

 printf("%x\n", ~a);  //line 2

I solved it like

32 in hex is 20.
0000 0000 0010 0000
now tilde operator complements it
1111 1111 1101 1111 = ffdf.

I am confused how to solve it when I have

printf("%d\n", ~a);  //line 2 i.e %d NOT %x.

Solution

  • In your C implementation, as in most modern implementations of any programming language, signed integers are represented with two’s complement.

    In two’s complement, the high bit indicates a negative number, and the values are encoded as in these samples:

    Bits  Decimal
    0…011 +3
    0…010 +2
    0…001 +1
    0…000  0
    1…111 -1
    1…110 -2
    1…101 -3
    

    Thus, if the usual (unsigned) binary value for the bits is n and the high bit is zero, the represented value is +n. However, if the high bit is one, then the represented value is n-2w, where w is the width (the number of bits in the format).

    So, in an unsigned 32-bit format, 32 one bits would normally be 4,294,967,295. In a two’s complement 32-bit format, 32 one bits is 4,294,967,295 - 232 = -1.

    In your case, the bits you have are 1111 1111 1111 1111 1111 1111 1101 1111. In unsigned 32-bit format, that is 4,294,967,263. In two’s complement, it is 4,294,967,263 - 232 = -33.