Phase 3 of 30 · Topic 3.2

Bitwise Operations, BitMasks & Enum Flags Optimization

1Concept

Bitwise operations (`&`, `|`, `^`, `~`, `<<`, `>>`) operate directly on hardware CPU registers in a single clock cycle. `[Flags]` enums combine multiple distinct states into a compact 4-byte or 1-byte integer.

2Architecture Diagram

Permission BitMask (Single Byte Representation):
[ Read (1) ] | [ Write (2) ] | [ Execute (4) ] | [ Admin (8) ]
Binary: 0 0 0 0 1 1 0 1  ──> Has Read (1), Write (2), and Admin (8)

3Code Example

C# 13 & .NET 9
using System;

[Flags]
public enum SecurityFlags : byte
{
    None        = 0,
    Read        = 1 << 0, // 0001
    Write       = 1 << 1, // 0010
    Execute     = 1 << 2, // 0100
    AdminAccess = 1 << 3  // 1000
}

public class BitwiseFlagDemo
{
    public static void Main()
    {
        SecurityFlags userPerms = SecurityFlags.Read | SecurityFlags.Write;
        Console.WriteLine($"Assigned Permissions: {userPerms} (Raw: {(byte)userPerms})");

        // High-speed O(1) bitwise membership check
        bool canWrite = (userPerms & SecurityFlags.Write) != 0;
        bool isAdmin  = userPerms.HasFlag(SecurityFlags.AdminAccess);

        Console.WriteLine($"Can Write: {canWrite} | Is Admin: {isAdmin}");
    }
}

4Expected Output

Assigned Permissions: Read, Write (Raw: 3)
Can Write: True | Is Admin: False

5Key Takeaways

  • Use `(flags & target) != 0` for ultra-fast bit checking.
  • Always assign power-of-two values (`1 << N`) to flag enums.
  • Bitwise masks reduce database column count and memory footprint significantly.