C programming - bitwise complement operator

The bitwise complement operator ~ in C programming is a unary operator that is used to perform a bitwise NOT operation on an integer operand. It changes each 1 bit to 0 and each 0 bit to 1.

Here is an example of using the bitwise complement operator:

#include <stdio.h>

int main() {
  int num = 42; // 00101010 in binary
  int result = ~num;

  printf("result = %d\n", result);

  return 0;
}
Source:ww‮igi.w‬ftidea.com

In this example, we declared an integer variable num and initialized it with the value 42, which is equal to the binary value 00101010. We used the bitwise complement operator to perform a bitwise NOT operation on num, and stored the result in the integer variable result. The result of the bitwise NOT operation is 11010101 in binary, which is equal to -43 in two's complement representation.

The output of the program will be:

result = -43

The bitwise complement operator is useful in situations where we need to invert the bits of an integer. For example, we can use the bitwise complement operator to create a mask that has all bits set to 1 except for one specific bit.

#include <stdio.h>

int main() {
  int mask = ~(1 << 3); // create a mask with all bits set to 1 except for the 4th bit
  printf("mask = %d\n", mask);

  return 0;
}

In this example, we used the bitwise shift operator << to shift the value 1 to the left by 3 bits, which results in the binary value 00001000. We then used the bitwise complement operator to invert the bits of this value, which results in the binary value 11110111. This is a mask that has all bits set to 1 except for the 4th bit, which is equal to 0.

The output of the program will be:

mask = -8

In summary, the bitwise complement operator ~ in C programming is a unary operator that is used to perform a bitwise NOT operation on an integer operand. It changes each 1 bit to 0 and each 0 bit to 1. The bitwise complement operator is useful in situations where we need to invert the bits of an integer, or create a mask with all bits set to 1 except for one specific bit.