Skip to content

Latest commit

 

History

History
48 lines (33 loc) · 1.48 KB

File metadata and controls

48 lines (33 loc) · 1.48 KB

8-BIT ALU (Arithmetic Logic Unit) IN PYTHON

This project came in mind after diving into low-level computer architecture and wanting to understand how CPUs actually do arithmetic at the bit level.

Core Features

  • Built from first principles: Half adder (XOR + AND) -> full adder -> 8-bit ripple-carry addition. No + and - operators for the core logic.
  • Two's complement substraction: Invert, add 1, then add. It reuses the same adder; no separate substraction hardware.
  • Status flags: Z (zero), N (negative/MSB), O (signed overflow) update after each operation. Matches the kind of flags that are in real CPUs.
  • Opcode-based execute(): 0 = add, 1 = sub. Inputs are masked to 8 bits (0xFF);

What It Demonstrates

  • Bitwise operations (&, |, ^, ~, <<, >>) and 8-bit masking
  • Signed overflow (e.g. 127 + 1 -> 128 interpreted as -128)
  • Unsigned overflow (e.g 255 + 1 -> 0)
  • Zero flag (e.g. 5 + 251 = 0), negative flag (MSB set)

Usage

from main import ALU
alu = ALU()

# Add: 10 + 15 = 25
result = alu.execute(0,10,15)

# Substract: 10 - 3 = 7
result = alu.execute(1,10,3)

# Inspect flags
# alu.flags['Z'] -> zero
# alu.flags['N'] -> negative (MSB)
# alu.flags['O'] -> signed overflow

Testing

Tests cover basic add/sub, zero flag, signed overflow (127 + 1), and unsigned overflow (255 + 1). All assertions include flag checks where relevant.

Running the Tests:

python test_main.py
or
pytest test_main.py -v