This is a unary operator. This means it needs one variable to do the operation. This operator first converts variables in binary then does complement operation and at the end, it converts the result to its previous data type.
Let us see what happens when we do bitwise complement operation with any two bits.
Syntax : ~<1st variable>;
From the below table, we can say that output is the exact opposite of the input.
a |
~a |
0 |
1 |
1 |
0 |
Now let us take an example of multiple bits.
a = 10;
We want the result of ~a so convert a in binary. The binary representation of the integer variable is 8 bits.
a(binary) = 0000 1010
For ~a, each individual bit will be complemented. We can understand it with different colors as shown below. So the result of ~a is 5 (binary 0101)
~ ( 0 0 0 0 1 0 1 0 ) = ( 1 1 1 1 0 1 0 1 ) = 245
But for any int number, its complement is always represented by its 2’s complement. So,
2’s complement of 245 = 2’s complement of ( 1 1 1 1 0 1 0 1 ) = – ( 0 0 0 0 1 0 1 1 ) = -11
In the below program there are two int variables: a, c. a is having value 4 and c is ~a. Now,
~a = ~ 4(binary 00000100)
= 2’s complement of 11111011
= – (00000101)
= -5
Which is printed.
#include<stdio.h> #include<conio.h> void main() { int a=4,c; clrscr(); c = ~a; printf("c = %d ",c); getch(); }
Output:
Learning from this blog:
- Need of bitwise complement operator.
- Characteristic of bitwise complement.
- How can we find a complement of any number?
- Why do we need 2’s complement for doing a complement of any int number.
- How to write the program of bitwise complement operators.