对于班级项目,我至少需要读取一个文件,以获取MIPS指令,例如:
add $t0, $s1, $s4
addi $t1, $a0, 7
等等...(我可以根据需要创建文件,而我只需要担心I和R格式) 我的问题是从文件中读取并首先将其实际转换为二进制,然后将二进制转换为十六进制应该不难。 我只是不确定如何正确阅读说明并将其转换为二进制。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX 10
#define SIZE 128
struct{
const char *name;
char *address;
}registers[] = {{ "zero", "00000"},
{ "at", "00001" },
{ "v0", "00010" },
{ "v1", "00011" },
{ "a0", "00100" },
{ "a1", "00101" },
{ "a2", "00110" },
{ "a3", "00111" },
{ "t0", "01000" },
{ "t1", "01001" },
{ "t2", "01010" },
{ "t3", "01011" },
{ "t4", "01100" },
{ "t5", "01101" },
{ "t6", "01110" },
{ "t7", "01111" },
{ "s0", "10000" },
{ "s1", "10001" },
{ "s2", "10010" },
{ "s3", "10011" },
{ "s4", "10100" },
{ "s5", "10101" },
{ "s6", "10110" },
{ "s7", "10111" },
{ "t8", "11000" },
{ "t9", "11001" },
{ NULL, 0 } };
struct{
const char *name;
char *function;
}rInst[] = {{ "add", "100000" },
{ "sub", "100001" },
{ "and", "100100" },
{ "or", "100101" },
{ "sll", "000000" },
{ "slt", "101010" },
{ "srl", "000010" },
{ "jr", "001000" },
{ NULL, 0 } };
struct {
const char *name;
char *function;
} iInst[] = {{ "lw", "100011" },
{ "sw", "101011" },
{ "andi", "001100" },
{ "ori", "001101" },
{ "lui", "001111" },
{ "beq", "000100" },
{ "slti", "001010" },
{ "addi", "001000" },
{ NULL, 0 } };
struct inst{
char opcode[MAX];
char register1[MAX];
char register2[MAX];
char register3[MAX];
int num;
struct inst *next;
}*first, *current;
int main(){
FILE *fp = fopen( "/home/js0939/CompOrg/MIPSLab5.txt", "r");
char *result[10][4];
char line[SIZE];
char *value;
if(fp == NULL){
printf("Error.");
return 1;
}
int i=0;
int j=0;
int k=0;
int l=0;
char* func;
char* reg;
// loop through each entry in file
while(fgets(line, sizeof(line), fp)){
//retrieves instruction
value = strtok(line, " ");
result[i][0] = strdup(value);
for (i = 0; rInst[i].name != NULL; i++) {
if (strcmp(value, rInst[i].name) == 0) {
func = rInst[i].function;
printf("%s ", func);
}
}
for (i = 0; iInst[i].name != NULL; i++) {
if (strcmp(value, iInst[i].name) == 0) {
func = iInst[i].function;
printf("%s ", func);
}
}
//retrieves first register
value = strtok(NULL, " ");
result[i][1] = strdup(value);
printf("%s ", value);
for (i = 0; registers[i].name != NULL; i++){
if(strcmp(value, registers[i].address) == 0){
reg = registers[i].address;
printf("%s ", reg);
}
}
//retreives second register
value = strtok(NULL, " ");
result[i][2] = strdup(value);
printf("%s ", value);
for (i = 0; registers[i].name != NULL; i++){
if(strcmp(value, registers[i].address) == 0){
reg = registers[i].address;
printf("%s ", reg);
}
}
//retreives third register
value = strtok(NULL, " \n");
result[i][3] = strdup(value);
printf("%s ", value);
for (i = 0; registers[i].name != NULL; i++){
if(strcmp(value, registers[i].address) == 0){
reg = registers[i].address;
printf("%s ", reg);
}
}
//go to next line
printf("\n");
i++;
}
fclose(fp);
return 0;
}