--- id: c-bitwise-operators title: "C Bitwise Operators" category: "Programming_Language" status: "draft" verification_status: "conceptual" canonical_id: "" aliases: ["& | ^ ~ << >>", "flags and permissions", "two's complement", "C 비트 연산자"] duplicate_of: "" source_trust_level: "B" confidence_score: 0.86 created_at: 2026-07-04 updated_at: 2026-07-04 review_reason: "" merge_history: [] tags: ["c", "programming-language", "w3schools", "operators", "bitwise"] raw_sources: ["https://www.w3schools.com/c/c_bitwise_operators.php"] applied_in: [] github_commit: "" --- # [[C Bitwise Operators]] ## 🎯 한 줄 통찰 (One-line insight) The bitwise NOT example (`~5` = `-6`) only makes sense once you know C stores negative numbers via TWO'S COMPLEMENT — flipping `00000101` (5) bit-by-bit gives `11111010`, which under two's complement representation is interpreted as -6, not some arbitrary large positive number — meaning `~` behaves "unexpectedly" only if you forget that the CPU's negative-number encoding, not simple bit-flipping intuition, determines the final printed value. [S1] ## 🧠 핵심 개념 (Core concepts) - **Six bitwise operators** — `&` (AND, 1 only if both bits 1), `|` (OR, 1 if either bit 1), `^` (XOR, 1 only if bits differ), `~` (NOT, inverts all bits), `<<` (left shift, multiplies by powers of 2), `>>` (right shift, divides by powers of 2). [S1] - **Integer-only operation** — bitwise operators only work on integer types (`int`, `char`, `long`), not floats. [S1] - **Two's complement interpretation** — `~a` inverting bits produces a result whose printed decimal value depends on how negative numbers are stored (typically two's complement). [S1] - **Flags pattern** — combining multiple boolean options into one integer using distinct bit positions (`#define READ 1`, `#define WRITE 2`, `#define EXEC 4`), then checking each with `&`. [S1] - **Shift as multiply/divide by powers of 2** — `a << n` multiplies `a` by 2ⁿ; `a >> n` divides `a` by 2ⁿ (sign bit may be preserved on signed integers, system-dependent). [S1] ## 📖 세부 내용 (Details) - Full worked example with `a = 6` (0110) and `b = 3` (0011): `a & b` = 2 (0010), `a | b` = 7 (0111), `a ^ b` = 5 (0101), `~a` = -7 on most systems, `a << 1` = 12 (1100), `a >> 1` = 3 (0011). [S1] - Bitwise NOT and two's complement: `int a = 5; // 00000101 int result = ~a; // -6 on most systems` — because inverted bits `11111010` are interpreted as -6 under two's complement. [S1] - Flags/permissions pattern: `#define READ 1 #define WRITE 2 #define EXEC 4 int permissions = READ | WRITE; if (permissions & READ) { printf("Read allowed\n"); } if (permissions & WRITE) { printf("Write allowed\n"); } if (permissions & EXEC) { printf("Execute allowed\n"); }` — only Read/Write print, since EXEC was never OR'd in. [S1] ## ⚖️ 모순 및 업데이트 (Contradictions & updates) - **~ 연산 결과는 이진수 반전 자체가 아니라 2의 보수 해석에 좌우됨**: 5(00000101)를 반전하면 11111010이 되는데, 이를 그대로 큰 양수로 읽는 것이 아니라 대부분의 시스템에서 -6으로 해석된다는 점(2의 보수 표현)이 명시적으로 설명됨. [S1] ## 🛠️ 적용 사례 (Applied in summary) READ/WRITE/EXEC 권한을 하나의 정수에 비트 플래그로 저장하고 &로 개별 권한을 검사하는 패턴이 원문에서 직접 실전 활용 사례로 제시됨(파일 시스템 권한 모델의 기초). [S1] ## 💻 코드 패턴 (Code patterns) Storing multiple boolean options in a single integer using bit flags (C): ```c #define READ 1 // 0001 #define WRITE 2 // 0010 #define EXEC 4 // 0100 int permissions = READ | WRITE; // user can read and write if (permissions & READ) { printf("Read allowed\n"); } if (permissions & WRITE) { printf("Write allowed\n"); } if (permissions & EXEC) { printf("Execute allowed\n"); } // not printed ``` ## ✅ 검증 상태 및 신뢰도 - **상태:** draft - **검증 단계:** conceptual - **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body) - **신뢰 점수:** 0.86 - **중복 검사 결과:** 신규 생성 (New discovery) ## 🔗 지식 그래프 (Knowledge Graph) - **상위/루트:** [[C Tutorial]] - **관련 개념:** [[C Operators Logical]], [[C Operators Assignment]], [[C Operators Precedence]] - **참조 맥락:** 비트 연산자 — 연산자 우선순위(Operators Precedence) 챕터로 이어짐. ## 📚 출처 (Sources) - [S1] W3Schools — C Bitwise Operators — https://www.w3schools.com/c/c_bitwise_operators.php ## 📝 변경 이력 (Change history) - 2026-07-04: Initial draft synthesized from the W3Schools "C Bitwise Operators" page (Astra wiki-curation, P-Reinforce v3.1 format).