C Bitwise Complement Operator

In C, the Bitwise Complement ~ operator is a unary operator that inverts all the bits of an operand. This means that every 0 bit becomes 1 and every 1 bit becomes 0. The result of applying the bitwise complement operator is the two’s complement representation of the operand, which is equivalent to -(n + 1).


Syntax of the Bitwise Complement Operator

The syntax to use the Bitwise Complement operator is:

</>
Copy
~operand

Explanation:

  1. operand: The integer value whose bits will be inverted.
  2. ~: The bitwise complement operator that flips all bits of the operand.
  3. Return Value: The result is -(operand + 1), as the bitwise complement represents the negative counterpart in two’s complement notation.

Examples of the Bitwise Complement Operator

1. Using Bitwise Complement on a Positive Integer

In this example, we will apply the bitwise complement operator to a positive integer and print the result.

main.c

</>
Copy
#include <stdio.h>

int main() {
    int num = 5;
    int result = ~num;

    printf("Bitwise complement of %d is %d\n", num, result);

    return 0;
}

Explanation:

  1. We declare an integer variable num with value 5.
  2. We apply the bitwise complement operator ~ to num and store the result in result.
  3. Since ~5 is equivalent to -(5 + 1) = -6, the output is -6.
  4. We use printf() to display the original and complemented values.

Output:

Bitwise complement of 5 is -6

2. Using Bitwise Complement on a Negative Integer

In this example, we will apply the bitwise complement operator to a negative integer.

main.c

</>
Copy
#include <stdio.h>

int main() {
    int num = -3;
    int result = ~num;

    printf("Bitwise complement of %d is %d\n", num, result);

    return 0;
}

Explanation:

  1. We declare an integer variable num with value -3.
  2. We apply the bitwise complement operator ~ to num and store the result in result.
  3. Since ~(-3) is equivalent to -(-3 + 1) = 2, the output is 2.
  4. We use printf() to display the result.

Output:

Bitwise complement of -3 is 2

3. Using Bitwise Complement in an Expression

In this example, we will use the bitwise complement operator inside an arithmetic expression.

main.c

</>
Copy
#include <stdio.h>

int main() {
    int num = 8;
    int result = ~num + 2;

    printf("Result of ~%d + 2 is %d\n", num, result);

    return 0;
}

Explanation:

  1. We declare an integer variable num with value 8.
  2. We apply the bitwise complement ~ to num, which gives -9 (-(8 + 1)).
  3. We add 2 to the result, so -9 + 2 equals -7.
  4. We use printf() to display the final result.

Output:

Result of ~8 + 2 is -7

Conclusion

In this tutorial, we covered the Bitwise Complement ~ operator in C:

  1. The Bitwise Complement operator ~ inverts all bits of an integer.
  2. The result follows the formula -(operand + 1).
  3. It is useful in low-level programming, bitwise operations, and expressions.