
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Differences Between Bitwise and Logical AND Operators in C/C++
As we know the bit-wise AND is represented as ?&' and the logical operator is represented as ?&&'. There are some fundamental differences between them. These are as follows ?
bitwise AND operator
The bitwise AND (&) operator performs a bit-by-bit AND operation between two integers. The bitwise AND operator works on integer, short int, long, unsigned int type data, and also returns that type of data. Here, Each bit should be 1 to give the result as 1, else it will result in 0,
- 1 & 1 = 1
1 & 0 = 0
0 & 1 = 0
0 & 0 = 0
logical AND operator
The logical AND (&&) operator in programming is used to combine two conditions or Boolean expressions. It works on Boolean expressions and returns Boolean values only. Here If either or both conditions are false, it will result in false.
- True && True = True
True && False = False
False && True = False
False && False = False
Example
Here is the following example showcasing the difference between bitwise and logical AND operators.
#include<iostream> using namespace std; int main() { int x = 3; //...0011 int y = 7; //...0111 if (y > 1 && y > x) cout << "y is greater than 1 AND x" << endl; int z = x & y; // 0011 cout << "z = "<< z; }
Output
y is greater than 1 AND x z = 3
Explanation
- In the first case Logical AND(&&) is used, So the condition will check y > 1, which is true (as y=7), and y > x, which is also true, So the logical operator will result in True if both conditions are true.
- In bitwise AND operator (&), it will compare each bit of x and y, if both bits are 1, it will result in 1 else 0.
- x: 0011
& y: 0111
z: 0011 (In decimal 3), Therefore 3 will be stored in the z variable.
Example 2
Here is another example demonstrating the use of logical vs bitwise AND operator.
#include<iostream> using namespace std; int main() { int x = 0; cout << (x && printf("Test using && ")) << endl; cout << (x & printf("Test using & ")); }
Output
0 Test using & 0