C programming bitwise operators; Through this tutorial, you will learn bitwise operators in C programming with examples.
A bitwise operator is an operator used to perform bitwise operations on bit patterns or binary numerals that involve the manipulation of individual bits.
C Programming Bitwise Operators
List of C Programming Bitwise Operators
| Operators | Meaning of operators |
|---|---|
| & | Bitwise AND |
| | | Bitwise OR |
| ^ | Bitwise XOR |
| ~ | Bitwise complement |
| << | Shift left |
| >> | Shift right |
Bitwise AND operator &
The bitwise operator is represented by a single ampersand sign (&) and it is very commonly used.The result of the bitwise AND operation is 1 if both the bits have the value as 1; otherwise, the result is always 0.
Example 1 – Bitwise AND Operator
#include <stdio.h>
int main()
{
int a = 12, b = 25;
printf("Output = %d", a&b);
return 0;
}
Output
Output = 8
Bitwise OR operator |
The output of bitwise OR is 1 if at least one corresponding bit of two operands is 1. In C Programming, the bitwise OR operator is denoted by |.
Example 1 – Bitwise OR Operator
#include <stdio.h>
int main()
{
int a = 12, b = 25;
printf("Output = %d", a|b);
return 0;
}
Output
Output = 29
Bitwise XOR (exclusive OR) operator ^
This is represented by a symbol (^). Two integer expressions are written on each side of the (^) operator.
The result of the bitwise Exclusive-OR operation is 1 if only one of the expression has the value as 1; otherwise, the result is always 0.
Example 1 – Bitwise XOR Operator
#include <stdio.h>
int main()
{
int a = 12, b = 25;
printf("Output = %d", a^b);
return 0;
}
Output
Output = 21
Bitwise complement operator ~
Bitwise complement operator is a unary operator (works on only one operand). It changes 1 to 0 and 0 to 1. It is denoted by ~.
Example 1 – Bitwise complement Operator
#include <stdio.h>
int main()
{
printf("Output = %d\n",~35);
printf("Output = %d\n",~-12);
return 0;
}
Output
Output = -36 Output = 11
Shift Operators in C programming
There are two shift operators in C programming:
- Right shift operator
- Left shift operator.
Right Shift Operator
Right shift operator shifts all bits towards right by certain number of specified bits. It is denoted by >>.
Left Shift Operator
Left shift operator shifts all bits towards left by a certain number of specified bits. The bit positions that have been vacated by the left shift operator are filled with 0. The symbol of the left shift operator is <<.
Example 1 – Shift Operators
#include <stdio.h>
int main()
{
int num=212, i;
for (i=0; i<=2; ++i)
printf("Right shift by %d: %d\n", i, num>>i);
printf("\n");
for (i=0; i<=2; ++i)
printf("Left shift by %d: %d\n", i, num<<i);
return 0;
}
Output
Right Shift by 0: 212 Right Shift by 1: 106 Right Shift by 2: 53 Left Shift by 0: 212 Left Shift by 1: 424 Left Shift by 2: 848