Hi, I am trying to code a brookshear machine and I am getting weird results with my code.
My Code:
Code:
#include <stdio.h>
void display_values(unsigned int pc, unsigned char mem[], unsigned char reg[]);
FILE *f;
int main() {
unsigned int pc = 0, i = 0, temp = 0;
unsigned char reg[16], mem[256], a, b, c, d, cd;
for(i = 0; i < sizeof(reg); i++) {
reg[i] = 0x00;
}
for(i = 0; i < sizeof(mem); i++) {
mem[i] = 0x00;
}
f = fopen("a3.txt", "r");
if(f == NULL) {
printf("Error: File not found!\n");
return 0;
}
while(fscanf(f, "%X", &temp) != EOF) {
mem[i] = (temp & 0xff00) >> 8;
mem[i+1] = temp & 0xff;
i+=2;
}
fclose(f);
while(mem[pc] != 0xC0) {
a = (mem[i] & 0xf0) >> 4;
b = mem[i] & 0xf;
c = (mem[i+1] & 0xf0) >> 4;
d = mem[i+1] & 0xf;
cd = mem[i+1];
display_values(pc, mem, reg);
if(a == 0x1) {
// Load the register R with the value at memory address XY.
reg[b] = mem[cd];
}
if(a == 0x2) {
// Load register R with the value XY.
reg[b] = cd;
}
if(a == 0x3) {
// Store the value in register R at memory address XY.
mem[cd] = reg[b];
}
if(a == 0x4) {
// Move the value in register R to register S.
reg[d] = reg[c];
reg[c] = 0x00;
}
if(a == 0x5) {
// Add(+) values in registers R and S and put the answer in register T.
reg[d] = reg[b] + reg[c];
}
if(a == 0x7) {
// Bit-wise OR(|) the values in registers R and S and put the answer in register T.
reg[d] = reg[b] | reg[c];
}
if(a == 0x8) {
// Bit-wise AND(&) the values in registers R and S and put the answer in register T.
reg[d] = reg[b] & reg[c];
}
if(a == 0x9) {
// Bit-wise XOR(^) the values in registers R and S and put the answer in register T.
reg[d] = reg[b] ^ reg[c];
}
if(a == 0xA) {
// Rotate the contents of register R X times to the right.
reg[b] >>= 1;
reg[b] = reg[b] | ((reg[b] & 0x1) << 31);
}
if(a == 0xB) {
// Jump to the instruction located at memory address XY if register R = register 0.
if(mem[b] == reg[0]) {
pc = cd;
}
}
pc = pc + 2;
display_values(pc, mem, reg);
}
return 0;
}
void display_values(unsigned int pc, unsigned char mem[], unsigned char reg[]) {
unsigned int i = 0;
printf("%02X", pc);
printf(" %02X%02X ", mem[pc], mem[pc+1]);
for(i = 0; i < sizeof(reg); i++) {
printf(" %02X ", reg[i]);
}
printf("\n");
}
I am reading from a text file that contains:
B404
239A
2412
5345
350C
C000
The right result is:
00 B404 – [00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00]
04 2412 - [00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00]
06 5345 - [00 00 00 00 12 00 00 00 00 00 00 00 00 00 00 00]
08 350C - [00 00 00 00 12 12 00 00 00 00 00 00 00 00 00 00]
0A C000 - [00 00 00 00 12 12 00 00 00 00 00 00 00 00 00 00]
But I am getting: (Note: it started from 00...)
Need help.