Bitwise OR |
What you'll learn: How to use the Bitwise OR operator to combine bits and turn specific flags "on" within a variable.
The Logical Safety Net
Imagine a row of light switches. The Bitwise OR operator, represented by the single pipe symbol |, acts like a rule for flipping those switches. When you OR two numbers together, you are comparing them bit by bit (position by position).
The rule is simple: if either the first bit OR the second bit is a 1, the resulting bit is a 1. The only way to get a 0 is if both bits are 0. Think of it as a "safety net" for electricity—if there is a power source coming from anywhere, the light turns on.
Visualizing the Operation
Computers see the number 5 as 0101 and the number 6 as 0110. If we apply 5 | 6, we look at each column:
- Rightmost column:
1OR0=1 - Second column:
0OR1=1 - Third column:
1OR1=1 - Fourth column:
0OR0=0
The result is 0111, which is the number 7 in decimal. Even though 5 + 6 is 11, 5 | 6 is 7. This is because bitwise operators care about the internal binary pattern, not the sum of the values.
Why Use This?
In C, we often use Bitwise OR to "set" flags. Imagine you are writing code for a game character. You might have a variable where the first bit means "is alive" and the second bit means "has sword." If you want to give a character a sword without changing whether they are alive or dead, you OR their current status with the "sword" bit. It ensures that specific switch is flipped to 1 regardless of its previous state.
Code Example
#include <stdio.h>
int main() {
// Binary: 0000 1010
int permissions = 10;
// Binary: 0000 0100
int read_access = 4;
// Using | to combine them
// 1010 | 0100 = 1110 (which is 14)
int updated_permissions = permissions | read_access;
printf("Original: %d\n", permissions);
printf("After OR: %d\n", updated_permissions);
return 0;
}
Key takeaway
The Bitwise OR | returns a 1 if at least one of the corresponding bits is 1, making it the primary tool for "turning on" specific bits in a value.