所以我试图用 C 语言编写一个基本的汇编程序,它将接收两个文件,一个输入和一个输出。输入将包含指令,输出将包含汇编代码,例如可以使用“od -x output.txt | head -5”查看。然而,我的问题是如何为分支指令做到这一点?下面提供的是添加指令,它也会产生一个我不太理解的奇怪输出,在“add R2 R4 R1”的手动组装中,它应该产生“1241”的输出,但它会产生“4112”的输出。为什么这样做?
PR1.C
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char *ltrim(char *s) {
while (*s == ' ' || *s == '\t') s++;
return s;
}
char getRegister(char *text) {
if (*text == 'r' || *text=='R') text++;
return atoi(text);
}
int assembleLine(char *text, unsigned char* bytes) {
text = ltrim(text);
char *keyWord = strtok(text," ");
if (strcmp("add",keyWord) == 0) {
bytes[0] = 0x10;
bytes[0] |= getRegister(strtok(NULL," "));
bytes[1] = getRegister(strtok(NULL," ")) << 4 | getRegister(strtok(NULL," "));
return 2;
}
}
int main(int argc, char **argv) {
FILE *src = fopen(argv[1],"r");
FILE *dst = fopen(argv[2],"w");
while (!feof(src)) {
unsigned char bytes[4];
char line[1000];
if (NULL != fgets(line, 1000, src)) {
printf ("read: %s\n",line);
int byteCount = assembleLine(line,bytes);
fwrite(bytes,byteCount,1,dst);
}
}
fclose(src);
fclose(dst);
return 0;
}