题目:做一个反汇编器,将16进制码转化成汇编指令。
分析:模拟。输入都是合法的按顺序解析即可。
这里有两个问题:
1.指令的格式为:命令+参数(不同指令参数不同,但不变);
2.指令可能分布在相邻的两行,如果发现余下长度不够,则劈接到下一次开头;
说明:(⊙v⊙),发现排名提升了(新的排名算法?)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char cmd_list[16][5] = {
"ADD", "SUB", "MUL", "DIV", "MOV",
"BREQ", "BRLE", "BRLS", "BRGE", "BRGR", "BRNE", "BR",
"AND", "OR", "XOR", "NOT",
};
int par_list[16] = {
2, 2, 2, 2, 2,
1, 1, 1, 1, 1, 1, 1,
3, 3, 3, 1,
};
int char_to_hex(char c)
{
if (c >= '0' && c <= '9') {
return c-'0';
}else {
return c-'A'+10;
}
}
char mod_list[4][4] = {"R", "$", "PC+", ""};
void par_print(char str[], int now)
{
int mode = char_to_hex(str[now])>>2;
int value = char_to_hex(str[now])-(mode<<2);
for (int i = 1; i < 4; ++ i) {
value = value*16 + char_to_hex(str[now+i]);
}
printf("%s%d",mod_list[mode],value);
}
int disassembly(char str[], int end)
{
int move = 0;
while (str[move]) {
int index = char_to_hex(str[move]);
// half hex command
if (move+1+par_list[index]*4 > end) {
return move;
}
printf("%s ",cmd_list[index]);
move ++;
for (int i = 0; i < par_list[index]; ++ i) {
if (i) {
printf(",");
}
par_print(str, move);
move += 4;
}
printf("\n");
}
return move;
}
int main()
{
char buf[100], ass[100];
int save = 0;
while (~scanf("%s",&buf[save])) {
int end = strlen(buf);
strcpy(ass, buf);
int left = disassembly(ass, end);
save = 0;
while (left < end) {
buf[save ++] = ass[left ++];
}
}
return 0;
}