C Bitwise AND Operator
In C, the Bitwise AND & operator is used to perform a bitwise AND operation between two integers at the binary level. It compares each bit of both operands and returns 1 if both bits are 1; otherwise, it returns 0.
The Bitwise AND operator is commonly used for bit masking and checking specific bits.
Syntax of the Bitwise AND Operator
The syntax to use the Bitwise AND operator is:
result = operand1 & operand2;
Explanation:
operand1: The first integer operand.&: The Bitwise AND operator.operand2: The second integer operand.result: The result of the bitwise AND operation. Each bit inresultis1if both corresponding bits inoperand1andoperand2are1, otherwise, it is0.
Examples of the Bitwise AND Operator
1. Using Bitwise AND on Two Integers
In this example, we will apply the Bitwise AND & operator on two integers and display the result.
main.c
#include <stdio.h>
int main() {
int a = 5, b = 3;
int result = a & b;
printf("Bitwise AND of %d and %d is %d\n", a, b, result);
return 0;
}
Explanation:
- The variables
aandbare initialized with values5(0101 in binary) and3(0011 in binary). - The Bitwise AND operation
a & bcompares each bit:
0101 (5)
& 0011 (3)
--------
0001 (1)
- The result
1(0001 in binary) is stored inresultand printed.
Output:
Bitwise AND of 5 and 3 is 1
2. Checking If a Number is Even Using Bitwise AND
In this example, we will use the Bitwise AND & operator to check if a number is even.
main.c
#include <stdio.h>
int main() {
int num = 10;
if (num & 1) {
printf("%d is Odd\n", num);
} else {
printf("%d is Even\n", num);
}
return 0;
}
Explanation:
- The integer variable
numis assigned a value of10. - The expression
num & 1checks the least significant bit (LSB) ofnum. - Since
10in binary is1010, performing10 & 1results in0(even number). - If the result is
0, the number is even; otherwise, it is odd.
Output:
10 is Even
3. Bitwise AND for Bit Masking
In this example, we will use the Bitwise AND & operator to check if a specific bit in a number is set.
main.c
#include <stdio.h>
int main() {
int num = 42; // Binary: 101010
int mask = 8; // Binary: 001000
if (num & mask) {
printf("The 4th bit is set.\n");
} else {
printf("The 4th bit is not set.\n");
}
return 0;
}
Explanation:
- The integer variable
numis assigned the value42(binary:101010). - The
maskvariable is set to8(binary:001000), which checks the 4th bit. - The bitwise AND operation
num & maskchecks if the 4th bit ofnumis set. - If the result is nonzero, the bit is set; otherwise, it is not set.
Output:
The 4th bit is set.
Conclusion
In this tutorial, we covered the Bitwise AND & operator in C. Important points to remember are:
- The Bitwise AND
&operator compares each bit of two operands. - It returns
1where both bits are1, otherwise0. - Common use cases include bitwise operations, even/odd checking, and bit masking.
The Bitwise AND & operator is essential for low-level programming and bit manipulation.
