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:
~operand
Explanation:
operand
: The integer value whose bits will be inverted.~
: The bitwise complement operator that flips all bits of the operand.- 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
#include <stdio.h>
int main() {
int num = 5;
int result = ~num;
printf("Bitwise complement of %d is %d\n", num, result);
return 0;
}
Explanation:
- We declare an integer variable
num
with value5
. - We apply the bitwise complement operator
~
tonum
and store the result inresult
. - Since
~5
is equivalent to-(5 + 1) = -6
, the output is-6
. - 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
#include <stdio.h>
int main() {
int num = -3;
int result = ~num;
printf("Bitwise complement of %d is %d\n", num, result);
return 0;
}
Explanation:
- We declare an integer variable
num
with value-3
. - We apply the bitwise complement operator
~
tonum
and store the result inresult
. - Since
~(-3)
is equivalent to-(-3 + 1) = 2
, the output is2
. - 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
#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:
- We declare an integer variable
num
with value8
. - We apply the bitwise complement
~
tonum
, which gives-9
(-(8 + 1)
). - We add
2
to the result, so-9 + 2
equals-7
. - 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:
- The Bitwise Complement operator
~
inverts all bits of an integer. - The result follows the formula
-(operand + 1)
. - It is useful in low-level programming, bitwise operations, and expressions.