因此,对于我的任务,我必须用C模拟基本的机器语言。机器有16个寄存器(reg []),一个程序计数器(pc)和内存(mem []),所有这些都是无符号字符。说明从文件中读入,格式为:
B404(1RXY =加载寄存器R,其值为存储器地址XY)。所有数字均为十六进制。 C000是暂停命令。
现在我的问题是当我打印出指令(当存储在a,b,c,d和cd中时)b和d有前导零。如何摆脱它们,以便如上所述打印指令? (第48行)。
此外,我的一些if语句似乎没有被调用,好像我在其中放了一个printf()并且它们在文件中从不打印。 (第48至78行)。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main () {
FILE *file;
file = fopen("a3.txt","r");
unsigned int temp = 0;
unsigned char pc, mem[256], reg[16],a,b,c,d,cd;
unsigned int count;
count = 0;
pc = 0;
for (int i=0; i < 16;++i) {
reg[i] = 0;
}
if (file == NULL) {
printf("\n Error opening the file");
exit(0);
}
for (int i=0; !feof(file); i += 2) {
fscanf(file, "%X", &temp);
mem[i] = ((temp & 0xFF00) >> 8);
mem[i + 1] = (temp & 0xFF);
if (feof(file)) {
break; // exit from while
}
++count;
}
int fclose(FILE *file);
/*while (mem[pc] != 0xC0) {*/
for (unsigned int i=0; i < count-1;++i) {
if (mem[i] == 0xC0) {
break; // exit from for
exit(1);
}
cd = mem[pc + 1];
a = (mem[pc] & 0xF0);
b = (mem[pc] & 0xF);
c = (mem[pc + 1] & 0xF0);
d = (mem[pc + 1] & 0xF);
printf("%02X ",pc);
printf("%X%X%X%X - [",a,b,c,d);
printf("%02X %02X %02X %02X ",reg[0],reg[1],reg[2],reg[3]);
printf("%02X %02X %02X %02X ",reg[4],reg[5],reg[6],reg[7]);
printf("%02X %02X %02X %02X ",reg[8],reg[9],reg[10],reg[11]);
printf("%02X %02X %02X %02X]\n",reg[12],reg[13],reg[14],reg[15]);
if (a == 0x1) {
reg[b] = reg[cd];
}
if (a == 0x2) {
reg[b] = cd;
//printf("2 reporting in");
}
if (a == 0x3) {
reg[cd] = reg[b];
}
if (a == 0x4) {
reg[d] = reg[c];
}
if (a == 0x05) {
reg[d] = (reg[b] + reg[c]);
//printf("5 reporting in");
}
if (a == 0x7) {
reg[d] = (reg[b] | reg[c]);
}
if (a == 0x8) {
reg[d] = (reg[b] & reg[c]);
}
if (a == 0x9) {
reg[d] = (reg[b] ^ reg[c]);
}
if (a == 0xA0) {
reg[b] = (reg[b] >> reg[d]) | (reg[b] << (32 - reg[d]));
}
pc += 2;
if (a == 0xB0) {
//printf("B reporting in");
if (reg[b] == reg[0]) {
pc = cd;
}
}
}
return 0;
}
谢谢!
答案 0 :(得分:1)
要获取unsigned char的高位,请使用以下函数:
unsigned char hi(unsigned char bits) {
return (bits >> 4) & 0x0F;
}
当您执行指令调度时,最好使用switch
语句而不是if ... else if ... else
级联。然后,您可以使用简单的default: fprintf(stderr, "unknown instruction: %u\n", a); exit(1);
进行错误检测。
另外,0xA0
不是值10,而是160,所以你应该写10
或0x0A
。
<强>更新强>
提取a
,b
,c
和d
的代码应如下所示:
a = (mem[pc + 0] >> 4) & 0x0F;
b = (mem[pc + 0] >> 0) & 0x0F;
c = (mem[pc + 1] >> 4) & 0x0F;
d = (mem[pc + 1] >> 0) & 0x0F;
这很容易阅读,也很容易检查是否正确。可以清楚地看到统一处理,并且每个值都限制在[0x00;0x0F]
范围内。