Binary-NOT Operator ~

This page was translated by a robot.

The bitwise NOT operator converts all bits of an integer value to their opposite: 0becomes off 1and vice versa. This corresponds to the so-called one's complement .












01001001100101100000001011010010
10110110011010011111110100101101
#include <stdio.h>

void printbinary(int x){
  char str[33]; str[32] = '\0';
  int i = 32;
  while(i){i--; str[i] = (x & 1) + '0'; x>>=1;}
  printf("%s\n", str);
}

int main(){
  int x = 1234567890;
  printbinary( x);
  printbinary(~x);
  return 0;
}

Details

The bitwise NOT operator expects an operand as rvalue and is processed from right to left . The return value is an rvalue , which is always an integer type.

The bitwise NOT operator is only allowed for integer values. Under C++, the use of the operator on boolean values ​​is also permitted, but these are intconverted into one before the operator is used.

The difference between the bitwise and the logical variant of the NOT operator is sometimes difficult for those new to the language to understand. The difference is: the bitwise variant changes all bits of values, the logical variant changes 1-bit values. Even with experienced programmers it happens that due to the similar spelling ( ~or !) the wrong operator is used by mistake and without realizing it. Also, since in certain cases (for example, when applying the operator to the value -1) the two operators return the same results, this is a hard-to-find source of errors that sometimes takes hours of debugging.

The bitwise NOT operator is often used for masks .