# Main loop of the Finite State Machine

This is a discussion on Main loop of the Finite State Machine within the C Programming forums, part of the General Programming Boards category; hey folks, i got an issue wtih this code I coded main loop of the finite state machine,I know the ...

1. ## Main loop of the Finite State Machine

hey folks, i got an issue wtih this code

I coded main loop of the finite state machine,I know the AND INSTRUCTION part but i could not figure out ADD INSTRUCTİON PART.

I hope you will help me out. Here is the code:

Code:
```// Main loop of the Finite State Machine
while (1)
{
// Fetch
instruction = memory[pc];
++pc;

// Decode
opcode = (instruction & 0xF000) >> 12;
printf("Opcode is %x\n", opcode);

switch (opcode)
{
case 0x0:
printf("Branch instruction.\n");
break;

case 0x1:
printf("ADD instruction\n");
// HERE. I COULD NOT FIGURE OUT
break;

case 0x5:
printf("AND instruction\n");
if (instruction & (1 << 5))
{
// Immediate mode
dr = (instruction >> 8) & 0x7;
sr1 = (instruction >> 5) & 0x7;
store(dr, registers[sr1] & sign_extend(5, instruction & 0x1F));
}
else
{
// Immediate mode
dr = (instruction >> 8) & 0x7;
sr1 = (instruction >> 5) & 0x7;
sr2 = (instruction >> 0) & 0x7;
store(dr, registers[sr1] & registers[sr2]);
}
break;

case 0x9:
printf("NOT instruction\n");
break;

case 0xF:
/* Right now, quit any time we see a trap. */
exit(0);
}
}

}```

2. I'm assuming then, that the ADD instruction is supposed to add the values in 2 registers (or a register and immediate value) and store them somewhere. The code should look exactly like your AND code, except that you're using the addition operator '+' instead of the and operator, '&'.

Can you describe exactly what's wrong with ADD mode? What is the type of registers? Perhaps this is a signed vs unsigned issue or an overflow issue.

Code:
```	  else
{
// Immediate mode
dr = (instruction >> 8) & 0x7;
sr1 = (instruction >> 5) & 0x7;
sr2 = (instruction >> 0) & 0x7;
store(dr, registers[sr1] & registers[sr2]);
}```
I think the else clause is "direct mode" (using 2 register), not "immediate mode" (using a registers and literal/immediate value).

3. nhnty
Nice...

4. @ makonikor
Please don't edit your posts down to nothing (or garbage) as soon as you've got your answer.
No one else can learn from the discussion if you do that.

Popular pages Recent additions