Language 1 of 10 · Topic 0.4

Operators, Precedence & Bitwise Manipulation

1Concept

C supports arithmetic (+, -, *, /, %), relational, logical (&&, || with short-circuit evaluation), and hardware-level bitwise operators: & (AND), | (OR), ^ (XOR), ~ (NOT), << (left shift), >> (right shift). Bitwise manipulation is essential for flags, network protocols, embedded registers, and cryptographic primitives.

2Architecture Diagram

Bitwise Operations on Byte:
  0000 1101  (13)
& 0000 0111  (7)
-------------
  0000 0101  (5)  [Bitwise AND]

Masking Bit 3: flags |= (1 << 3)   [Set Bit 3]
Clearing Bit 3: flags &= ~(1 << 3)  [Clear Bit 3]

3Code Example

Stage 0 Language Foundations
#include <stdio.h>

#define FLAG_READ    (1 << 0) // 0001 = 1
#define FLAG_WRITE   (1 << 1) // 0010 = 2
#define FLAG_EXECUTE (1 << 2) // 0100 = 4

int main(void) {
    unsigned char permissions = 0;

    // Set READ and WRITE permissions
    permissions |= (FLAG_READ | FLAG_WRITE);
    printf("Permissions after setting READ & WRITE: 0x%02X (%d)\n", permissions, permissions);

    // Check EXECUTE permission
    if (permissions & FLAG_EXECUTE) {
        printf("Has Execute permission: YES\n");
    } else {
        printf("Has Execute permission: NO\n");
    }

    // Toggle (XOR) EXECUTE permission on
    permissions ^= FLAG_EXECUTE;
    printf("Has Execute after XOR toggle: %s\n", (permissions & FLAG_EXECUTE) ? "YES" : "NO");

    return 0;
}

4Expected Output

Permissions after setting READ & WRITE: 0x03 (3)
Has Execute permission: NO
Has Execute after XOR toggle: YES

5Key Takeaways

  • Use (1 << n) to create bit masks for the nth bit.
  • Logical && and || short-circuit; right-hand side is not evaluated if left determines result.
  • Integer division between ints truncates decimals towards zero.