Debugging Bitwise Permission Errors

90% of bitwise bugs are preventable. Learn the top 5 errors and their fixes.

Always print binary when debugging permissions!

1. Binary Debug Function (Essential)

C
Print binary representation
#include <stdio.h>
void printBinary(unsigned int n) {
    printf("Binary: ");
    for (int i = 10; i >= 0; i--)
        printf("%d", (n >> i) & 1);
    printf(" (%u)\n", n);
}

2. Bug #1: Missing Tilde (Most Common)

C
WRONG vs CORRECT revoke
// ❌ BUG: Permission stays set!
perms &= READ;  // 00100 & 00100 = 00100

// ✅ FIX
perms &= ~READ; // 00100 & 11011 = 00000

printBinary(perms);  // SEE the difference!

3. Bug #2: Signed Octal Constants

C
Signed vs unsigned disaster
// ❌ BUG: Negative values!
int perms = 0400;  // -384! Sign extended

// ✅ FIX
unsigned int perms = 0400U;  // 256 ✓

printBinary(perms);  // Reveals truth

4. Bug #3: Wrong Test Logic

C
Confusing but working vs clear
// ❌ Confusing
if ((perms & MASK) == MASK)

// ✅ Clear and simple
if (perms & MASK)

// Both work, but 2nd is readable

5. Bug #4: Mask Overlap

C
Wrong bit positions
#define USER_R 0400  // bit 9
#define GROUP_R 0040  // bit 6

// DEBUG:
printBinary(USER_R);  // 00100000000
printBinary(GROUP_R); // 00000100000
// Bits don't overlap ✓

6. Bug #5: Precedence Trap

C
Operator precedence error
// ❌ BUG: Compares first!
if (perms & READ == 0)

// ✅ FIX: Parentheses
if ((perms & READ) == 0)

// Or better:
if (!(perms & READ))

7. Systematic Debug Process

TEXT
5-step debug checklist
1. Print binary BEFORE/AFTER operation
2. Verify mask = correct bit (1,2,4,8...)
3. Use 'unsigned int' for perms
4. Check for missing ~ in &= operations
5. Add parentheses around & in if conditions

8. Correct Permission Manager

C
Bulletproof implementation
#include <stdio.h>
#define READ 1
#define WRITE 2
unsigned int perms = 0;

void printBinary(unsigned int n) {
    for(int i=3;i>=0;i--) printf("%d",(n>>i)&1);
    printf(" (%u)\n",n);
}

int main() {
    perms |= READ | WRITE;   // 0110
    printBinary(perms);
    perms &= ~READ;          // 0010
    printBinary(perms);
    return 0;
}

Conclusion

Golden Rule: Print binary when bitwise goes wrong.

90% of bugs visible instantly with binary output.