The Bitwise OR Operator (|)
What You'll Learn
You'll learn how the bitwise OR operator (|) combines two integer values by returning 1 whenever either corresponding bit is 1.
How Bitwise OR Works
The bitwise OR operator (|) examines each pair of corresponding bits in two integer values and produces a new value following one simple rule: if either bit (or both) is 1, the result bit is 1. Only when both bits are 0 does the result bit become 0.
Think of it like asking "Is at least one light switch on?" If either switch (or both) is flipped to "on," the answer is yes.
Bit-by-Bit Comparison
Let's walk through an example with small values:
int a = 12; // Binary: 1100
int b = 10; // Binary: 1010
int result = a | b; // Binary: 1110, which is 14
Here's what happens bit by bit:
1100 (12)
| 1010 (10)
------
1110 (14)
- Position 3 (leftmost):
1 | 1 = 1 - Position 2:
1 | 0 = 1 - Position 1:
0 | 1 = 1 - Position 0 (rightmost):
0 | 0 = 0
The bitwise OR "turns on" any bit that's set in either operand.
Another Example
int x = 5; // Binary: 0101
int y = 3; // Binary: 0011
int z = x | y; // Binary: 0111, which is 7
Notice how all the 1 bits from both numbers appear in the result.
Key Takeaway: The bitwise OR operator (|) produces 1 for each bit position where at least one operand has a 1, making it useful for combining or "setting" bits in integer values.