Project 3: Bitwise Logic Calculator

  • File: P03-bitwise-logic-calculator.md
  • Main Programming Language: C
  • Alternative Programming Languages: Rust, Go, Python
  • Coolness Level: Level 2 (See REFERENCE.md)
  • Business Potential: Level 1 (See REFERENCE.md)
  • Difficulty: Level 2 (See REFERENCE.md)
  • Knowledge Area: Bitwise Logic
  • Software or Tool: CLI
  • Main Book: “Computer Systems: A Programmer’s Perspective”

What you will build: A CLI tool that performs AND, OR, XOR, NOT, and shift operations and prints results in binary and hex.

Why it teaches binary/hex: Bitwise operations act directly on bit patterns.

Core challenges you will face:

  • Operator semantics -> Bitwise Operations
  • Shift validation -> Bitwise Operations
  • Binary formatting -> Bits/Bytes/Nibbles

Real World Outcome

$ bitcalc AND 0xF0 0x3C
result_hex: 0x30
result_bin: 00110000

The Core Question You Are Answering

“How do I control individual bits inside a number?”

Concepts You Must Understand First

  1. Bitwise operators
    • What does AND/OR/XOR/NOT do per bit?
    • Book Reference: “Computer Systems: A Programmer’s Perspective” - Ch. 2
  2. Shifts
    • What are safe shift counts?
    • Book Reference: “Computer Systems: A Programmer’s Perspective” - Ch. 2

Questions to Guide Your Design

  1. Input parsing
    • Will you allow decimal and hex input?
    • How will you display binary output consistently?
  2. Validation
    • How will you reject invalid shift amounts?
    • How will you handle negative inputs?

Thinking Exercise

Mask Reasoning

Given a mask 0x0F, explain which bits are preserved after AND.

Questions to answer:

  • Which bits survive an AND with 0x0F?
  • What would OR with 0x80 do?

The Interview Questions They Will Ask

  1. “Explain how AND is used to test a flag.”
  2. “What is the difference between logical and bitwise operators?”
  3. “Why is shifting by 32 undefined for a 32-bit integer?”
  4. “How would you toggle bit 7?”
  5. “What is XOR useful for?”

Hints in Layers

Hint 1: Starting Point Implement each operator separately and print both hex and binary results.

Hint 2: Next Level Normalize inputs to unsigned values before shifting.

Hint 3: Technical Details Pseudocode:

result = apply_op(op, a, b)
print hex(result)
print bin(result, width=8 or 16)

Hint 4: Tools/Debugging Use a trusted language REPL to compare outputs for random inputs.

Books That Will Help

Topic Book Chapter
Bitwise operators “Computer Systems: A Programmer’s Perspective” Ch. 2

Common Pitfalls and Debugging

Problem 1: “My shifts produce garbage”

  • Why: You are shifting signed values or shifting too far.
  • Fix: Use unsigned values and validate shift counts.
  • Quick test: Shift 1 left by 1, 2, 3 and verify powers of two.

Definition of Done

  • Supports AND, OR, XOR, NOT, «, »
  • Prints results in hex and binary
  • Validates shift amounts
  • Includes a test suite of known vectors