Bitwise OR Operation Basics
Learn how the bitwise OR (|) operator works. OR returns 1 when at least one of the corresponding bits is 1. Used for setting flags and combining bitmasks.
Detailed Explanation
Understanding Bitwise OR (|)
The OR operator compares each pair of corresponding bits. The result bit is 1 when at least one of the input bits is 1. It is 0 only when both bits are 0.
Truth Table
A | B | A | B
--|---|------
0 | 0 | 0
0 | 1 | 1
1 | 0 | 1
1 | 1 | 1
Worked Example
Let's compute 42 | 15:
42 = 00101010
| 15 = 00001111
──────────────────
47 = 00101111
Every bit position that has a 1 in either operand produces a 1 in the result.
Setting Bits with OR
The primary use of OR is to set specific bits to 1 without affecting other bits. ORing any bit with 1 forces it to 1, while ORing with 0 leaves the original value unchanged. This is the complement of AND's masking behavior.
Combining Flags
In flag-based systems, each flag occupies a unique bit position. You combine multiple flags using OR:
const READ = 0b001; // 1
const WRITE = 0b010; // 2
const EXECUTE = 0b100; // 4
const permissions = READ | WRITE; // 0b011 = 3
This pattern is used extensively in operating systems, graphics APIs (OpenGL, Vulkan), and configuration libraries.
Idempotence
OR is idempotent for setting bits: if a bit is already 1, ORing it with 1 again still produces 1. This means you can safely "add" a flag without checking whether it is already set.
Use Case
Game developers combine feature flags using OR to build composite configuration values. For instance, a rendering pipeline might combine DEPTH_TEST | ALPHA_BLEND | CULL_FACE into a single integer that represents all enabled render states, then pass it to the GPU driver in one call instead of multiple state-change calls.