Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 3

#include <stdio.

h>

#define LOAD_MEM 0
#define LOAD_VAL 1
#define STORE 2
#define ADD 3
#define SUB 4
#define MUL 5
#define DIV 6
#define INC 7
#define DEC 8
#define AND 9
#define OR 10
#define NOT 11
#define JMP 12
#define JZ 13
#define JNZ 14
#define HLT 15

unsigned char GetOpcode ( short instruction ){


return instruction >> 8;
}

unsigned char GetOperand ( short instruction ){


return instruction & 0xFF;
}

int main() {

FILE * file = fopen("SP1Assembler.c", "rb" );

short program[256];

short instruction;

int i = 0;

while( fread( &instruction, 2, 1, file ) != 0 ){


program[i] = instruction;
i++;
}

int pc = 0;
short mem[256];
int operando = 0;
int carry = 0;
int overflow = 0;

unsigned char acc = 0;


unsigned char stat = 0;

while(1){
unsigned char opcode = GetOpcode( program[pc] );

switch( opcode ){

case LOAD_MEM:
operando = GetOperand( program[pc] );
acc = mem [ operando];
break;

case LOAD_VAL:
operando = GetOperand( program[pc] );
acc = operando;
break;

case STORE:
operando = GetOperand( program[pc] );
mem[operando] = acc;
break;

case ADD:
operando = GetOperand( program[pc] );
acc = acc + mem[ operando ];
if( acc >= 256)
++carry;
break;

case SUB:
operando = GetOperand( program[pc] );
acc = acc - mem[ operando ];
break;

case MUL:
operando = GetOperand( program[pc] );
acc = acc * mem[ operando ];
if( acc >= 256)
++overflow;
break;

case DIV:
operando = GetOperand( program[pc] );
acc = acc / mem[ operando ];
break;

case INC:
++acc;
break;

case DEC:
--acc;
break;

case AND:
operando = GetOperand( program[pc] );
acc = acc & mem[ operando];
break;

case OR:
operando = GetOperand( program[pc] );
acc = acc | mem[ operando];
break;

case NOT:
acc = ~ acc;
break;

case JMP:
operando = GetOperand( program[pc] );
pc = operando -1; // -1 pq depois do switch tem um ++pc;
break;

case JZ:
operando = GetOperand( program[pc] );
if(acc == 0)
pc = operando -1; // -1 pq depois do switch tem um ++pc;
break;

case JNZ:
operando = GetOperand( program[pc] );
if (acc != 0)
pc = operando -1; // -1 pq depois do switch tem um ++pc;
break;

case HLT:
printf("acc: %u\n", (unsigned int)acc);
printf("stat: 00000");
if(overflow >= 1)
printf("1");
else{
printf("0");
}
if(carry >= 1)
printf("1");
else{
printf("0");
}
if(acc == 0)
printf("1");
else{
printf("0");
}
fclose(file);
return 0;
}
++pc;
}
return 0;
}

You might also like