Bitwise operators in C programming
Bitwise Operators in C
Bitwise operators in C are used to perform operations on the binary representations of integers. They operate on the individual bits of data and are essential for low-level programming tasks such as bit manipulation. Here’s an overview of the bitwise operators available in C:
1. Bitwise AND Operator (&&
)
The &
operator performs a bitwise AND operation between two integers. Each bit in the result is set to 1 if both corresponding bits in the operands are 1.
int a = 12; // Binary: 00001100
int b = 7; // Binary: 00000111
int result = a & b; // Result: 00000100 (4 in decimal)
printf("%d", result); // Output: 4
2. Bitwise OR Operator (|
)
The |
operator performs a bitwise OR operation between two integers. Each bit in the result is set to 1 if at least one of the corresponding bits in the operands is 1.
int a = 12; // Binary: 00001100
int b = 7; // Binary: 00000111
int result = a | b; // Result: 00001111 (15 in decimal)
printf("%d", result); // Output: 15
3. Bitwise XOR Operator (^
)
The ^
operator performs a bitwise XOR (exclusive OR) operation between two integers. Each bit in the result is set to 1 if only one of the corresponding bits in the operands is 1.
int a = 12; // Binary: 00001100
int b = 7; // Binary: 00000111
int result = a ^ b; // Result: 00001011 (11 in decimal)
printf("%d", result); // Output: 11
4. Bitwise NOT Operator (~
)
The ~
operator performs a bitwise NOT operation, which inverts all the bits in an integer. The result is the one's complement of the operand.
int a = 12; // Binary: 00001100
int result = ~a; // Result: 11110011 (in decimal, -13 in signed representation)
printf("%d", result); // Output: -13
5. Left Shift Operator (<<
)
The <<
operator shifts the bits of the left operand to the left by the number of positions specified by the right operand. It effectively multiplies the number by 2 for each shift.
int a = 5; // Binary: 00000101
int result = a << 2; // Result: 00010100 (20 in decimal)
printf("%d", result); // Output: 20
6. Right Shift Operator (>>
)
The >>
operator shifts the bits of the left operand to the right by the number of positions specified by the right operand. It effectively divides the number by 2 for each shift.
int a = 20; // Binary: 00010100
int result = a >> 2; // Result: 00000101 (5 in decimal)
printf("%d", result); // Output: 5
Bitwise Operators Summary
Operator | Description | Example | Result |
---|---|---|---|
& |
Bitwise AND | a & b |
1 if both bits are 1 |
| |
Bitwise OR | a | b |
1 if at least one bit is 1 |
^ |
Bitwise XOR | a ^ b |
1 if only one bit is 1 |
~ |
Bitwise NOT | ~a |
Inverts all bits |
<< |
Left Shift | a << n |
Shifts bits to the left |
>> |
Right Shift | a >> n |
Shifts bits to the right |
Comments
Post a Comment