Bitwise Operators in C
Bitwise operators in C operate on individual bits of integer operands. They are used for low-level programming, such as setting, clearing, and toggling bits.
Bitwise AND (&)
Performs logical AND on each bit of two integers. The result bit is 1 only if both corresponding bits are 1.
Example: a & b
Bitwise OR (|)
Performs logical OR on each bit of two integers. The result bit is 1 if either of the corresponding bits is 1.
Example: a | b
Bitwise XOR (^)
Performs logical XOR on each bit. The result bit is 1 if the corresponding bits are different.
Example: a ^ b
Bitwise NOT (~)
Inverts all the bits of the operand (0 becomes 1, 1 becomes 0).
Example: ~a
Left Shift (<<)
Shifts the bits of the operand to the left by the specified number of positions. Vacated bits are filled with 0.
Example: a << 2 // shifts bits of a left by 2 positions
Right Shift (>>)
Shifts the bits of the operand to the right by the specified number of positions. Vacated bits depend on the type (0 for unsigned, sign bit for signed).
Example: a >> 2 // shifts bits of a right by 2 positions
Key Points
- Bitwise operators work only on integer types
- Useful in embedded programming, flags, masks, and performance optimization
- Operate directly on the binary representation of numbers
- Order of precedence: ~ > << >> > & > ^ > |
Common Mistakes
- Using bitwise operators instead of logical operators accidentally
- Assuming results are decimal values without considering binary effect
- Shifting by more than the number of bits in the type
- Not using parentheses in complex expressions (operator precedence matters)
Codecrown