Understanding Bitwise Operators in C: A Beginner's Guide
The bitwise operators are the operators used to perform the operations on the data at the bit-level. When we perform the bitwise operations, then it is also known as bit-level programming. It consists of two digits, either 0 or 1. It is mainly used in numerical computations to make the calculations faster.
Operator | Description |
| | Bitwise OR |
& | Bitwise AND |
^ | Bitwise XOR |
~ | Bitwise NOT |
<< | Left shift |
>> | Signed right shift |
The code is a C program that demonstrates the use of bitwise operators in C. Here is an explanation of each line of the code:
- int a=25,b=45,c; declares variables a, b, and c of type int and assigns them the values 25, 45 and 0 respectively.
- printf("\n Bitwise And : %d",a&b); uses the bitwise AND operator '&' to perform a bitwise AND operation on variables a and b and then prints the result.
- printf("\n Bitwise Or : %d",a|b); uses the bitwise OR operator '|' to perform a bitwise OR operation on variables a and b and then prints the result.
- printf("\n Bitwise Xor : %d",a^b); uses the bitwise XOR operator '^' to perform a bitwise XOR operation on variables a and b and then prints the result.
- printf("\n Bitwise Not : %d",~a); uses the bitwise NOT operator '~' to perform a bitwise NOT operation on variable a and then prints the result.
- a=16; assigns value 16 to a
- b=a<<2; uses Left shift operator to shift the bits of a 2 position to left
- c=a>>2; uses Right shift operator to shift the bits of a 2 position to right
- printf("\n Left Shift : %d",b); prints the Left shifted value of a
- printf("\n Right Shift : %d",c); prints the Right shifted value of a
- return 0; The return 0; statement is used to indicate that the main function has completed successfully. The value 0 is returned as the exit status of the program, which indicates a successful execution.
Source Code
//Bitwise Operators
#include<stdio.h>
int main()
{
int a=25,b=45,c;
printf("\n Bitwise And : %d",a&b);
printf("\n Bitwise Or : %d",a|b);
printf("\n Bitwise Xor : %d",a^b);
printf("\n Bitwise Not : %d",~a);
a=16;
b=a<<2;
c=a>>2;
printf("\n Left Shift : %d",b);
printf("\n Right Shift : %d",c);
return 0;
}
To download raw file
Click Here
Output
Bitwise And : 9
Bitwise Or : 61
Bitwise Xor : 52
Bitwise Not : -26
Left Shift : 64
Right Shift : 4