10432 - hw2 - instruction simulator   

Description

 The x97 CPU has 4 32 bits registers, r0, r1, r2, and r3, whose initial values are all zeros. The CPU has 2 kinds of instructions, MOV and ADD, whose formats are specified as follows.

1.      MOV , : assign constant C to register 1.

2.      MOV , : copy the content of register 2 to register 1.

3.      ADD , : add the value of register 1 and constant C, and save the result to register 1.

4.      ADD , : add the value of register 1 and the value of register 2, and save the result to register 1.

 

  

Hint:

You can use the following code to get the input and to print the output.

#include

#include

#include

enum code {MOV, ADD};

enum op_type {REG, CONST};

typedef struct INST {

    enum code opcode;

    enum op_type op1;

    int operand1_value;

    enum op_type op2;

    int operand2_value;

    struct INST* next;

} INST;

/* read input from stdin. */

INST* readInput(){

    char opc[10], op1[10], op2[10];

    int ns=0, c;

    INST *head=0, *curr=0;

    ns = scanf("%s %s %d ", opc, op1, &c);

    while(ns > 0) {

        /* allocate a storage for an instruction */

        if (head == 0){

            head = (INST*) malloc(sizeof(INST));

            curr = head;

            curr->next = 0;

        } else {

            curr->next = (INST*) malloc(sizeof(INST));

            curr = curr->next;

            curr->next = 0;

        }

       /* set the content of the instruction.*/

        /* opcode */

        if (strcmp(opc, "MOV")==0)

            curr->opcode = MOV;

        else if (strcmp(opc, "ADD")==0)

            curr->opcode = ADD;

        /* Since op1 is always a register, read its id.*/

        curr->op1 = REG;

        curr->operand1_value = op1[1]-'0';

        /* read operand 2.*/

        if (ns == 2){  /* operand 2 is a register*/

            scanf("%s ", op2);

            curr->op2 = REG;

            curr->operand2_value = op2[1] -'0';

        } else if (ns == 3) { /* operand 2 is a constant.*/

            curr->op2 = CONST;

            curr->operand2_value = c;

        }

        /* get next one*/

        ns = scanf("%s %s %d ", opc, op1, &c);

    }

    return head;

}

 

Input

 The input is a list of instructions.

Output

 The output is the values of all register in the order of r0, r1, r2, and r3.

Use %4d for each resgister and print a newline in the end.

Sample Input  Download

Sample Output  Download

Tags




Discuss