Search code examples
c++bit-manipulationtilde

NOT operation on integer value


I knew that ~ operator does NOT operation. But I could not make out the output of the following program (which is -65536). What exactly is happening?

#include <stdio.h>

int main(void) {
  int  b = 0xFFFF;
  printf("%d",~b);
  return 0;
}

Solution

  • When you assign the 16-bit value 0xffff to the 32-bit integer b, the variable b actually becomes 0x0000ffff. This means when you do the bitwise complement it becomes 0xffff0000 which is the same as decimal -65536.