Representing the Machine with a struct

Representing the machine itself in C is fairly easy. We require two parts. One is the memory of the machine and the other is the processor. You'll find the C code containing the data structures for representing our machine in the emulate.h file. The memory is simply implemented as an array of 65536 bytes. Since the C char type is one byte, we simply implement the memory with the following line of code:

unsigned char mem[65536];

Alternatively, we could have used unsigned short int instead of unsigned char. The unsigned is simply used to specify that by default, each memory location will contain an unsigned value. We wouldn't want 5, 255 representing -1*256 + 5 = -251, so we need to treat the individual bytes of memory as unsigned numbers.

Remarkably, representing the internals of the processor in C is also not very difficult. We simply use a struct and typedef combination:

typedef struct machine
{
	int A, X, IP, SP;
	int REGS[7];
	bool C, Z, P;
	bool running;
} machine;

This defines a new type called machine which consists of a structure, also called machine. The structure contains fields for each of the internal parts of the processor.

Since the C type int usually represents 16 bits of storage, it is ideal for representing our registers inside the processor. Thus we have an int field inside our struct for the accumulator A, the segment register X, the instruction pointer IP and the stack pointer SP. Each of the 7 registers is also an int inside our struct. We implement the seven of them with an array of 7 ints, which we call REG. Thus REG[0] is the first of the registers, REG[1] is the second, etc.

Since the flags are either going to be set or clear, we can implement these with a field of type bool for each of them. We must remember to include the stdbool.h library with the following line:

#include <stdbool.h>

so that we can work with these fields of type bool.

Finally, we need some way to keep track of whether a program is running on our machine, or whether a HLT instruction has been encountered, and execution should cease. This is implemented with a field inside our processor, again of type bool. This is somewhat artificial, since most processors in real computers are executing something at all times. If it isn't executing a specific program, then it is running the operating system (even if just an idle loop), or just maintenance code which keeps track of the time or whatever.