Bitwise Operators in C ++
Bitwise Operators in C++
Bitwise operators in C++ work directly on the individual bits of integer data types (like int, char, short, long, etc.). They manipulate the binary representation of these values. Here's a breakdown of common bitwise operators:
1. Bitwise AND (&)
* Purpose: Performs a logical AND operation on corresponding bits of two operands.
* Result: 1 only if both corresponding bits are 1, otherwise 0.
int a = 5; // Binary: 0101
int b = 3; // Binary: 0011
int c = a & b; // Binary: 0001 (Decimal: 1)
2. Bitwise OR (|)
* Purpose: Performs a logical OR operation on corresponding bits of two operands.
* Result: 1 if at least one of the corresponding bits is 1, otherwise 0.
int a = 5; // Binary: 0101
int b = 3; // Binary: 0011
int c = a | b; // Binary: 0111 (Decimal: 7)
3. Bitwise XOR (^)
* Purpose: Performs a logical XOR (exclusive OR) operation on corresponding bits of two operands.
* Result: 1 if the corresponding bits are different, 0 if they are the same.
int a = 5; // Binary: 0101
int b = 3; // Binary: 0011
int c = a ^ b; // Binary: 0110 (Decimal: 6)
4. Bitwise NOT (~)
* Purpose: Flips the bits of the operand.
* Result: Inverts each bit (0 becomes 1, 1 becomes 0).
int a = 5; // Binary: 0101
int c = ~a; // Binary: 1010 (Two's complement representation of -6)
5. Left Shift (<<)
* Purpose: Shifts the bits of the first operand to the left by the number of positions specified by the second operand.
* Result: Equivalent to multiplying the first operand by 2 raised to the power of the second operand.
int a = 5; // Binary: 0101
int c = a << 2; // Binary: 10100 (Decimal: 20)
6. Right Shift (>>)
* Purpose: Shifts the bits of the first operand to the right by the number of positions specified by the second operand.
* Result: Equivalent to dividing the first operand by 2 raised to the power of the second operand (integer division).
int a = 5; // Binary: 0101
int c = a >> 1; // Binary: 0010 (Decimal: 2)
Common Uses of Bitwise Operators
* Checking and Setting Bits:
* Check if a specific bit is set (1) or not (0).
* Set a specific bit to 1.
* Clear a specific bit to 0.
* Toggle the state of a specific bit.
* Efficient Arithmetic Operations:
* Fast multiplication and division by powers of 2.
* Data Compression:
* Representing information in a more compact form.
* Image and Graphics Processing:
* Manipulating pixel data.
* Cryptography:
* Implementing encryption and decryption algorithms.
Example: Checking if a number is even or odd
#include <iostream>
using namespace std;
int main() {
int num = 7;
if (num & 1) {
cout << num << " is odd." << endl;
} else {
cout << num << " is even." << endl;
}
return 0;
}
Note:
* Bitwise operators can be used to write very efficient and concise code, but they can also make code harder to read if used excessively.
* Always consider readability and maintainability when using bitwise operators.
Comments
Post a Comment