ref: a7be9c155a2bd5fae1b795c69695e3448d1778e9
dir: /5551e.c/
/* 5551 cpu emulator */ #include <stdbool.h> #include <stdio.h> #include "5551.h" typedef struct { bool flags[8]; int regs[8]; }reg_t; bool add_bit(bool a, bool b, bool &carry) { bool out, temp, tcarry = carry; temp = a & b; out = ((a ^ b) | (temp & tcarry)); temp = a ^ b; carry = ((a & b) | (temp & tcarry)); return temp; } int main() { reg_t r; unsigned int memory[MMAX]; memory[MMAX-1] = -1; char string[16]; unsigned int op, a, b, c; /* there is no space between op and args since some can have no args */ while(scanf(r.flags[ON] && "%u%[^\n]", &op, string)) { sscanf(string, " %u %u", &a, &b, &c); switch(op) { case DIE: r.flags[ON] = 0; break; case OUT: /* just in case output is "manfi" */ if(r.flags[NSIGN]) printf("-%u\n", r.reg[a]); else printf("%u\n" r.reg[a]); break; case NOT: r.reg[b] = !a; break; case AND: r.reg[c] = a & b; break; case NOR: r.reg[c] = !(a | b) case XOR: r.reg[c] = a ^ b; break; case SUB: b = ~b; r.carry = 1; case ADD: r.reg[c] = add_bit(a, b, &r.flags[carry]); break; case SHR: r.reg[c] = reg[a] >> b; break; case SHL: r.reg[c] = reg[a] << b; break; case PUT: memory[b] = a; case MOV: memory[b] = reg[a]; break; case LDM: r.reg[b] = memory[a]; break; case NTH: r.reg[c] = a >> n; break; default: fprintf(stderr, "unkown op\n"); return 1; } /* clear them */ a = 0 b = 0 op = 0; string = ""; } return 0; }