add jnz, README.md

This commit is contained in:
krolxon 2026-01-04 19:10:23 +05:30
parent 244172960f
commit be61e5ae6b
4 changed files with 27 additions and 2 deletions

10
README.md Normal file
View File

@ -0,0 +1,10 @@
# 8-Bit CPU Simulator
## Added instructions
1. MOV
2. ADD
3. SUB
4. JMP (Jump)
5. JZ (Jump if zero)
5. JZ (Jump if not zero)
6. HLT (Halt)

View File

@ -153,4 +153,17 @@ impl CPU {
} }
pub fn jnz(&mut self, mem: &mut Memory) {
let low = mem.read(self.pc) as u16; self.inc_pc();
let high = mem.read(self.pc) as u16; self.inc_pc();
let addrs = (high << 8) | low;
if !self.zero {
self.pc = addrs;
}
}
} }

View File

@ -5,5 +5,6 @@ pub enum Instruction {
SUB = 0x03, SUB = 0x03,
JMP = 0x04, JMP = 0x04,
JZ = 0x05, JZ = 0x05,
JNZ = 0x06,
HLT = 0xFF, HLT = 0xFF,
} }

View File

@ -20,7 +20,7 @@ fn main() {
// b = 2 // b = 2
mem.write(0x0003, Instruction::MOV as u8); mem.write(0x0003, Instruction::MOV as u8);
mem.write(0x0004, 1); mem.write(0x0004, 1);
mem.write(0x0005, 5); mem.write(0x0005, 3);
// a = a + b // a = a + b
mem.write(0x0006, Instruction::SUB as u8); mem.write(0x0006, Instruction::SUB as u8);
@ -28,7 +28,7 @@ fn main() {
mem.write(0x0008, 1); mem.write(0x0008, 1);
// JMP to halt // JMP to halt
mem.write(0x0009, Instruction::JZ as u8); mem.write(0x0009, Instruction::JNZ as u8);
mem.write(0x000a, 0x0f); // Low mem.write(0x000a, 0x0f); // Low
mem.write(0x000b, 0x00); // High mem.write(0x000b, 0x00); // High
@ -50,6 +50,7 @@ fn main() {
x if x == Instruction::SUB as u8 => cpu.sub(&mut mem), x if x == Instruction::SUB as u8 => cpu.sub(&mut mem),
x if x == Instruction::JMP as u8 => cpu.jmp(&mut mem), x if x == Instruction::JMP as u8 => cpu.jmp(&mut mem),
x if x == Instruction::JZ as u8 => cpu.jz(&mut mem), x if x == Instruction::JZ as u8 => cpu.jz(&mut mem),
x if x == Instruction::JNZ as u8 => cpu.jnz(&mut mem),
x if x == Instruction::HLT as u8 => cpu.halt(), x if x == Instruction::HLT as u8 => cpu.halt(),
_ => panic!("Unknown opcode {:02X}", opcode), _ => panic!("Unknown opcode {:02X}", opcode),
} }