I'm having problems trying to create an assembly emulator program in C. There are 5 registers: REGA, REGB, REGC, REGX AND INSP, and 10 instructions: NOP, SET, AND (bitwise &), OR (bitwise |), ADD, SUB, SHL(<< left), SHR(>>), JMP.
The program reads instructions from a file; with lines containing the instruction and 2 arguments. In most cases the 1st argument is a register name (e.g. REGA) and the 2nd argument can be a register name or an integer.
I'm using sscanf to get the instructions from the file.
I'm having trouble with the ADD, SUB, SHL and SHR functions. My ADD function is:
int opcode_add(char* opcode, char *arg1, char *arg2){
int i, j;
for(i = 0; i < MAX_REGISTER; i++){
if (strcmp(register_str[i],arg1) == 0){
for(j = 0; j <=MAX_REGISTER; j++){
if(strcmp(register_str[j],arg2) == 0){
*register_ptr[i] = *register_ptr[i] + *register_ptr[j];
break;
}else {
*register_ptr[i] = *register_ptr[i] + atoi(arg2);
}
}
}
}
INSP++;
return (0);
}
The function works if 2 register arguments are passed. For example:
SET REGA 1
SET REGB 2
ADD REGA REGB
but not if a register and an integer are passed. For example:
SET REGA 2
ADD REGA 1
The problem is at this line:
*register_ptr[i] = *register_ptr[i] + atoi(arg2);
I tried doing this:
int y = *register_ptr[i];
int k = atoi(arg2);
int result = y+k;
*register_ptr[i] = result;
but it didn't work.
for(j = 0; j <=MAX_REGISTER; j++)The outerfor's terminating condition isi < MAX_REGISTERand both loops indexregister_str.