The Bitwise operators in C are some of the Operators used to perform bit operations. All the decimal values will convert into binary values (sequence of bits, i.e., 0100, 1100, 1000, 1001, etc.). Next, the bitwise operators will work on these bits, such as shifting them from left to right or converting bit values from 0 to 1.
The below table shows the different Bitwise operators in C Programming with example and their meanings. For example, Consider x = 6 and y = 8 and their values in binary form are: x = 0110 and y = 1000
Bitwise Operators | Meaning | Examples |
---|---|---|
& | Bitwise AND | X & Y = 0000 |
| | Bitwise OR | X | Y = 1110 |
^ | Bitwise exclusive OR | X ^ Y = 1110 |
~ | complement | ~X = 00001001 (Not operator will convert all 0 into 1.) |
<< | Shift left | X << 1 = 00001100 (Bits will move 1 step left. If we use 2 or 3, then they shift accordingly) |
>> | Shift right | Y >> 1 = 00000100 |
Let us see the Truth Table behind Bitwise Operators in C Programming Language
x | y | x & y | X | y | x ^ y |
---|---|---|---|---|
0 | 0 | 0 | 0 | 0 |
0 | 1 | 0 | 1 | 1 |
1 | 0 | 0 | 1 | 1 |
1 | 1 | 1 | 1 | 0 |
Bitwise operators in C Programming Example
Let us see one example to better understand bitwise operators. In this Program, We are using two variables, a and b, and their values are 9 and 65. Next, we will use these two variables to show you various operations.
We declared 2 integers in this c bitwise operators program, a and b, and assigned the values 9 and 65. The binary form of 9 = 0001001 and 65 = 1000001. The below printf statements will perform the bitwise operations on a and b then they will display the Program output
#include <stdio.h> int main() { int a = 9, b = 65; printf(" AND a&b = %d \n", a & b); printf(" OR a|b = %d \n", a | b); printf(" EXCLUSIVE OR a^b = %d \n", a ^ b); printf(" NOT ~a = %d \n", a = ~a); printf(" LEFT SHIFT a<<1 = %d \n", a << 1); printf(" RIGHT SHIFT b>>1 = %d \n", b >> 1); return 0; }
Let’s see the calculations behind these Operators in this Programming.
AND Operation = a & b
0001001 & 1000001 = 0000001 = 1
OR Operation = a || b
0001001 || 1000001 = 1001001 = 73
Next, Exclusive OR Operation = a ^ b
0001001 ^ 1000001 = 1001000 = 72
Left Shift Operation = b >> 1
1000001 >> 1 = 0100000 = 32