Bitwise operators in C allow you to manipulate individual bits of data directly. They are essential for tasks like masking, toggling, and setting flags, making them powerful tools for efficient programming and low-level data handling.
-
Bitwise AND (&)
- Compares each bit of two operands; results in 1 only if both bits are 1.
- Commonly used for masking bits to isolate specific bits in a number.
- Example:
5 & 3
results in 1
(binary: 0101 & 0011 = 0001
).
-
Bitwise OR (|)
- Compares each bit of two operands; results in 1 if at least one of the bits is 1.
- Useful for setting specific bits to 1 without affecting others.
- Example:
5 | 3
results in 7
(binary: 0101 | 0011 = 0111
).
-
Bitwise XOR (^)
- Compares each bit of two operands; results in 1 if the bits are different.
- Often used for toggling bits or checking for differences.
- Example:
5 ^ 3
results in 6
(binary: 0101 ^ 0011 = 0110
).
-
Bitwise NOT (~)
- Inverts all bits of the operand; 0 becomes 1 and 1 becomes 0.
- Useful for creating a complement of a binary number.
- Example:
~5
results in -6
(binary: ~0101 = 1010
in two's complement).
-
Left shift (<<)
- Shifts all bits of the operand to the left by a specified number of positions.
- Each left shift effectively multiplies the number by 2.
- Example:
5 << 1
results in 10
(binary: 0101 << 1 = 1010
).
-
Right shift (>>)
- Shifts all bits of the operand to the right by a specified number of positions.
- Each right shift effectively divides the number by 2 (for positive numbers).
- Example:
5 >> 1
results in 2
(binary: 0101 >> 1 = 0010
).
-
Bitwise assignment operators (&=, |=, ^=, <<=, >>=)
- Combine bitwise operations with assignment for concise code.
x &= y
is equivalent to x = x & y
, and similarly for other operators.
- Useful for updating values based on bitwise operations without redundancy.
-
Bitmasking
- Technique to manipulate specific bits in a number using masks.
- Masks are created using bitwise operators to isolate or modify bits.
- Commonly used in graphics, permissions, and flags.
-
Bit manipulation techniques
- Techniques include setting, clearing, toggling, and checking bits.
- Essential for efficient low-level programming and performance optimization.
- Examples:
x |= (1 << n)
sets the nth bit, x &= ~(1 << n)
clears it.
-
Bitwise operations for flag setting and checking
- Flags are represented as bits in a binary number, allowing multiple states in a single variable.
- Use bitwise operators to set, clear, or check flags efficiently.
- Example:
flags |= FLAG_A
sets FLAG_A, while flags & FLAG_A
checks if FLAG_A is set.