fork download
  1. #include <stdio.h>
  2.  
  3. int main() {
  4. // Define CPU registers
  5. int registers[4] = {0}; // Four general-purpose registers
  6.  
  7. // Program memory (instructions)
  8. int program[] = {0x1001, 0x2002, 0x3003, 0x4000}; // Sample instructions
  9.  
  10. // Instruction pointer
  11. int ip = 0;
  12.  
  13. // Emulation loop
  14. while (program[ip] != 0) {
  15. int instruction = program[ip];
  16. int opcode = (instruction >> 12) & 0xF;
  17. int operand1 = (instruction >> 8) & 0xF;
  18. int operand2 = instruction & 0xFF;
  19.  
  20. switch (opcode) {
  21. case 0x1: // Add
  22. registers[operand1] += operand2;
  23. break;
  24. case 0x2: // Subtract
  25. registers[operand1] -= operand2;
  26. break;
  27. case 0x3: // Jump if zero
  28. if (registers[operand1] == 0) {
  29. ip = operand2;
  30. continue; // Skip incrementing instruction pointer
  31. }
  32. break;
  33. case 0x4: // Halt
  34. return 0;
  35. }
  36. ip++;
  37. }
  38.  
  39. for (int i=0; i<4; i++){
  40. printf("registers[%d] = %d\n", i, registers[i]);
  41. }
  42. return 0;
  43. }
Success #stdin #stdout 0s 5308KB
stdin
Standard input is empty
stdout
Standard output is empty