Bitwise Operators in C: Usage and Examples
☰Fullscreen
Table of Content:
C language defines several bitwise operators, which can be applied to the integer types, long, int, short, char, and byte.
The following table lists the bitwise operators supported by C.
Assume variable 'R' holds 60 and variable 'S' holds 13, then ?
Operator | Description | Example |
---|---|---|
& (bitwise and) | Bitwise AND operator give true result if both operands are true. otherwise, it gives a false result. | (R & S) will give 12 which is 0000 1100 |
| (bitwise or) | Bitwise OR operator give true result if any of the operands is true. | (R | S) will give 61 which is 0011 1101 |
^ (bitwise XOR) | Bitwise Exclusive-OR Operator returns a true result if both the operands are different. otherwise, it returns a false result. | (R ^ S) will give 49 which is 0011 0001 |
~ (bitwise compliment) | Bitwise One's Complement Operator is unary Operator and it gives the result as an opposite bit. | (~R ) will give -61 which is 1100 0011 in 2's complement form due to a signed binary number. |
<< (left shift) | Binary Left Shift Operator. The left operands value is moved left by the number of bits specified by the right operand. | R << 2 will give 240 which is 1111 0000 |
>> (right shift) | Binary Right Shift Operator. The left operands value is moved right by the number of bits specified by the right operand. | R >> 2 will give 15 which is 1111 |
The following program is a simple example which demonstrates the Bitwise operators.
Bitwise AND Operator
Program
#include void main() { int A = 10; int B = 3; int Y; Y = A & B; printf("%d \n",Y); }
Output
2 Press any key to continue . . .
Bitwise OR Operator
Program
#include void main() { int A = 10; int B = 3; int Y; Y = A | B; printf("%d \n",Y); }
Output
11 Press any key to continue . . .
Bitwise XOR Operator
Program
#include void main() { int A = 10; int B = 3; int Y; Y = A ^ B; printf("%d \n",Y); }
Output
9 Press any key to continue . . .
Bitwise Compliment Operator
Program
#include void main() { int A = 10; int Y; Y = ~A ; printf("%d \n",Y); }
Output
-11 Press any key to continue . . .
Binary Right Shift Operator
Program
#include void main() { int x= 5; int y; y = x >> 2 ; printf("%d \n",y); }
Output
1 Press any key to continue . . .