Introduction to C Bitwise Operators
Bitwise operators are used to perform operations on the bits of a binary number. They are used in a variety of applications, such as data encryption, image processing, and networking.
Bitwise Operators in C
C has the following bitwise operators:
&
(bitwise AND)|
(bitwise OR)^
(bitwise XOR)~
(bitwise NOT)<<
(left shift)>>
(right shift)
Bitwise AND Operator
The bitwise AND operator (&
) copies a bit to the result if it exists in both operands. For example, the expression 1 & 2
will evaluate to 0, because only the leftmost bit of both operands is 1.
Bitwise OR Operator
The bitwise OR operator (|
) copies a bit to the result if it exists in either operand. For example, the expression 1 | 2
will evaluate to 3, because the leftmost bit of both operands is 1, and the rightmost bit of the second operand is 1.
Bitwise XOR Operator
The bitwise XOR operator (^
) copies a bit to the result if it is set in one operand but not both. For example, the expression 1 ^ 2
will evaluate to 3, because the leftmost bit of the first operand is 1, and the leftmost bit of the second operand is 0.
Bitwise NOT Operator
The bitwise NOT operator (~
) flips all the bits in a binary number. For example, the expression ~1
will evaluate to -2, because the binary representation of -2 is 10000001 in two’s complement notation.
Bitwise Left Shift Operator
The bitwise left shift operator (<<
) shifts the bits in a binary number to the left by a specified number of places. For example, the expression 1 << 2
will evaluate to 4, because the binary representation of 4 is 00000100 in two’s complement notation.
Bitwise Right Shift Operator
The bitwise right shift operator (>>``) shifts the bits in a binary number to the right by a specified number of places. For example, the expression
1 >> 2` will evaluate to 0, because the binary representation of 0 is 00000000 in two’s complement notation.
Bitwise Operators Examples
Here are some examples of how bitwise operators are used in C:
Conclusion
Bitwise operators are a powerful tool that can be used to perform a variety of tasks in C. By understanding how they work, you can write more concise and efficient code.