← CodeClarityLab Home
Browse by Category
+ added · updated 7d
← Back to glossary

Bit Manipulation

algorithms Intermediate

Also Known As

bitmask bitwise operators bitwise flags

TL;DR

Using bitwise operators (AND, OR, XOR, NOT, shifts) to manipulate individual bits — enabling compact storage, fast arithmetic, and O(1) set operations.

Explanation

Bitwise operators in PHP: & (AND), | (OR), ^ (XOR), ~ (NOT), << (left shift), >> (right shift). Common patterns: checking a bit (n & (1<<i)), setting a bit (n | (1<<i)), clearing a bit (n & ~(1<<i)), toggling a bit (n ^ (1<<i)). Applications: permission flags (user roles as bitmask), feature flags, fast powers of 2, parity checking, and space-efficient sets. Bitmasks are used in PHP's own API — error_reporting levels, PDO fetch modes, and PREG flags.

Watch Out

In PHP, & has lower operator precedence than == — the expression $x & FLAG == 1 evaluates as $x & (FLAG == 1), not ($x & FLAG) == 1. Always parenthesise bitwise checks.

Common Misconception

Bit manipulation is only for low-level systems programming — PHP uses bitmasks throughout its standard library; understanding them is needed to use error_reporting, PDO fetch modes, and file permissions correctly.

Why It Matters

PHP's own error_reporting, PDO::FETCH_*, and file permission octals all use bitmasks — misusing them produces subtle bugs like wrong error levels or incorrect fetch modes.

Common Mistakes

  • Using | to check if a flag is set — use & for checking: if ($flags & MY_FLAG) not if ($flags | MY_FLAG).
  • Not understanding that 0 is falsy — if ($flags & FLAG) is false when FLAG is not set AND when $flags is 0.
  • Integer overflow with large bitmasks in 32-bit PHP — use PHP_INT_SIZE to check word size.
  • Confusing ~ (bitwise NOT) with ! (logical NOT).

Avoid When

  • Avoid bitmasks when the set of flags is large, changes often, or needs to be queried individually in SQL — a junction table is more maintainable.
  • Do not use bitwise operators where boolean operators are intended — & vs && and | vs || have different short-circuit behaviour and precedence.
  • Avoid bit manipulation in domain logic where clarity matters more than micro-optimisation — future maintainers will not thank you.

When To Use

  • Use bitmasks to store multiple boolean flags in a single integer column — compact, fast to query, and easy to extend without schema changes.
  • Apply bitwise operations for performance-critical tight loops: power-of-two checks, fast modulo, flag testing in inner loops.
  • Use XOR for in-place swaps and simple checksums where readability is secondary to performance.

Code Examples

💡 Note
The bad example uses | (OR) to test a flag — it always returns non-zero and the check is always true. The fix uses & (AND) to mask the value and check whether that specific bit is set.
✗ Vulnerable
// Wrong operator for flag check — | always returns non-zero:
define('CAN_READ',   0b001); // 1
define('CAN_WRITE',  0b010); // 2
define('CAN_DELETE', 0b100); // 4

$permissions = CAN_READ; // User has read only
if ($permissions | CAN_WRITE) { // Bug: | always non-zero if either is set
    allowWrite(); // Always executes!
}
✓ Fixed
// Correct bitmask operations:
$permissions = CAN_READ | CAN_WRITE; // 0b011 = 3

// Check:
if ($permissions & CAN_WRITE)  { /* Has write permission */ }
if (!($permissions & CAN_DELETE)) { /* Does NOT have delete */ }

// PHP stdlib bitmask:
error_reporting(E_ALL & ~E_NOTICE); // All errors except notices
$stmt = $pdo->query($sql, PDO::FETCH_ASSOC | PDO::FETCH_UNIQUE);

Added 15 Mar 2026
Edited 31 Mar 2026
Views 20
Rate this term
No ratings yet
🤖 AI Guestbook educational data only
| |
Last 30 days
2 pings W 0 pings T 1 ping F 0 pings S 0 pings S 0 pings M 0 pings T 0 pings W 0 pings T 1 ping F 0 pings S 0 pings S 0 pings M 0 pings T 0 pings W 0 pings T 1 ping F 0 pings S 0 pings S 0 pings M 0 pings T 1 ping W 0 pings T 1 ping F 0 pings S 0 pings S 0 pings M 0 pings T 0 pings W 0 pings T
No pings yet today
No pings yesterday
Amazonbot 6 Perplexity 4 Ahrefs 2 Unknown AI 2
crawler 14
DEV INTEL Tools & Severity
🟢 Low ⚙ Fix effort: Medium
⚡ Quick Fix
Use bitwise operations for permission flags and feature toggles — a single integer can store 64 boolean flags and operations are O(1) vs array lookups
📦 Applies To
any web cli
🔗 Prerequisites
🔍 Detection Hints
65+ boolean columns for permissions; permission check with array_intersect when bitwise AND would work; PHP & | ^ << >> operators avoided
Auto-detectable: ✗ No phpstan
⚠ Related Problems
🤖 AI Agent
Confidence: Low False Positives: Medium ✗ Manual fix Fix: Medium Context: Function Tests: Update

✓ schema.org compliant