Table of Contents
There are various types of bitwise operators used in all the programming languages. Here is a list of the ones used in C:
The table below lists all the Bitwise operations that are supported by the C language. Let us assume that the variable ‘Q’ holds 13 while a variable ‘P’ holds 60, then:
Operator |
Meaning |
Description |
Examples |
| |
Bitwise OR operator |
It copies a bit when it exists in either of the operands. |
(P | Q) = 61, which is, 0011 1101 |
& |
Bitwise AND operator |
It copies a bit to the result when it exists in both the operands. |
(P & Q) = 12, which is, 0000 1100 |
~ |
Binary Ones complement operator |
It is a unary operator that has an effect to ‘flip’ the bits. Meaning, all the 0s become 1s and vice-versa. |
(~P ) = ~(60), which is,. 1100 0011 |
^ |
Bitwise XOR operator |
It is an exclusive OR operator that copies the bit when it is set in one of the operands, but not in both. |
(P | Q) = 61, which is, 0011 1101 |
>> |
Shift operator (Right) |
It moves the value of the left operand to the right by the number of bits that the right operand specifies. |
P >> 2 = 15 which is, 0000 1111 |
<< |
Shift operator (Left) |
It moves the value of the right operand to the left by the number of bits that the right operand specifies. |
P << 2 = 240 which is, 1111 0000 |
Let us look at the following example to understand how the bitwise operators work in the C language:
#include <stdio.h>
main() {
unsigned int p = 60; /* 60 = 0011 1100 */
unsigned int q = 13; /* 13 = 0000 1101 */
int r = 0;
r = p | q; /* 61 = 0011 1101 */
printf(“Line 1 – The value of r is %d\n”, r );
r = p & q; /* 12 = 0000 1100 */
printf(“Line 2 – The value of r is %d\n”, r );
r = ~p; /*-61 = 1100 0011 */
printf(“Line 3 – The value of r is %d\n”, r );
r = p ^ q; /* 49 = 0011 0001 */
printf(“Line 4 – The value of r is %d\n”, r );
r = p >> 2; /* 15 = 0000 1111 */
printf(“Line 5 – The value of r is %d\n”, r );
r = p << 2; /* 240 = 1111 0000 */
printf(“Line 6 – The value of r is %d\n”, r );
}