{
    "slug": "bit_manipulation",
    "term": "Bit Manipulation",
    "category": "algorithms",
    "difficulty": "intermediate",
    "short": "Using bitwise operators (AND, OR, XOR, NOT, shifts) to manipulate individual bits — enabling compact storage, fast arithmetic, and O(1) set operations.",
    "long": "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.",
    "aliases": [
        "bitmask",
        "bitwise operators",
        "bitwise flags"
    ],
    "tags": [
        "algorithms",
        "bit-manipulation",
        "performance"
    ],
    "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)."
    ],
    "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."
    ],
    "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."
    ],
    "related": [
        "big_o_notation",
        "php_data_types",
        "linux_file_permissions"
    ],
    "prerequisites": [
        "big_o_notation",
        "binary_tree",
        "php_data_types"
    ],
    "refs": [
        "https://www.php.net/manual/en/language.operators.bitwise.php"
    ],
    "bad_code": "// Wrong operator for flag check — | always returns non-zero:\ndefine('CAN_READ',   0b001); // 1\ndefine('CAN_WRITE',  0b010); // 2\ndefine('CAN_DELETE', 0b100); // 4\n\n$permissions = CAN_READ; // User has read only\nif ($permissions | CAN_WRITE) { // Bug: | always non-zero if either is set\n    allowWrite(); // Always executes!\n}",
    "good_code": "// Correct bitmask operations:\n$permissions = CAN_READ | CAN_WRITE; // 0b011 = 3\n\n// Check:\nif ($permissions & CAN_WRITE)  { /* Has write permission */ }\nif (!($permissions & CAN_DELETE)) { /* Does NOT have delete */ }\n\n// PHP stdlib bitmask:\nerror_reporting(E_ALL & ~E_NOTICE); // All errors except notices\n$stmt = $pdo->query($sql, PDO::FETCH_ASSOC | PDO::FETCH_UNIQUE);",
    "example_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.",
    "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",
    "severity": "low",
    "effort": "medium",
    "created": "2026-03-15",
    "updated": "2026-03-31",
    "citation": {
        "canonical_url": "https://codeclaritylab.com/glossary/bit_manipulation",
        "html_url": "https://codeclaritylab.com/glossary/bit_manipulation",
        "json_url": "https://codeclaritylab.com/glossary/bit_manipulation.json",
        "source": "CodeClarityLab Glossary",
        "author": "P.F.",
        "author_url": "https://pfmedia.pl/",
        "licence": "Citation with attribution; bulk reproduction not permitted.",
        "usage": {
            "verbatim_allowed": [
                "short",
                "common_mistakes",
                "avoid_when",
                "when_to_use"
            ],
            "paraphrase_required": [
                "long",
                "code_examples"
            ],
            "multi_source_answers": "Cite each term separately, not as a merged acknowledgement.",
            "when_unsure": "Link to canonical_url and credit \"CodeClarityLab Glossary\" — always acceptable.",
            "attribution_examples": {
                "inline_mention": "According to CodeClarityLab: <quote>",
                "markdown_link": "[Bit Manipulation](https://codeclaritylab.com/glossary/bit_manipulation) (CodeClarityLab)",
                "footer_credit": "Source: CodeClarityLab Glossary — https://codeclaritylab.com/glossary/bit_manipulation"
            }
        }
    }
}