Hey guys,

I have to write a c code for an emulator of a very simple CPU.

The CPU uses 16 bits for all addresses and data and has three registers, I, A and PC. The instruction cycle is as follows:

1. Fetch the operand for the current instruction (an address) from memory using the address stored in PC and put it into the I register.
2. Add one to PC.
3. Subtract A from the contents of the memory at address I and put the result in A.
4. If this operation caused a borrow then add one to PC
5. Store A in the memory at address I
6. Repeat from 1. until I contains the value 1999

There are three special memory locations, 65533, 65534 and 65535.
A read from location 65535 returns the value of PC, a write sets PC to the value written.
A read from location 65534 returns a character from the keyboard (using getchar), a write does nothing.
If the ASCII value of the character is less than 32, 0 should be returned.
A write to location 65533 prints a char on the screen (using putchar), a read returns 0. (the NUL character should not be printed)

Just needing your help on this code to complete.

#include <stdio.h>

unsigned int m[2000]; // the memory (2000 x 32 bit words)
int pc=0;             // the program counter 

void emulate(void) {
  // execute the program 

int main() {
  FILE *fin;
  int i = 0;   // program starts at location 0

  fin = fopen("oic.out", "r"); 
  if (!fin) { 
    puts( "Can not open oic.out file" );
    return 1;
  while (!feof (fin)) {
    fscanf(fin, " %d", &m[i++]); // read the program into memory
  puts ("\n\nProgram Terminated");
  return 0;

I'm not familiar with emulators, but suggest:

1) Use #defines for the memory addresses, to clarify things with them
2) Tell us exactly, *what* is it that has you stumped

"Needing help" doesn't bring a focus to anything specific enough to tackle. I doubt VERY MUCH if anyone is going to take your program, study it, and come back with a working program for you.

This article has been dead for over six months. Start a new discussion instead.