我怎样才能让我的汇编器翻译数字。它可以正确翻译其他指令,但不能正确翻译数字。任何帮助将不胜感激
这是我执行翻译的方法
```
private void assembler(String translation) {
String[] tokens = line.split("\\s*,\\s*"); // Split by comma
String opcode = tokens[0].toUpperCase(); // Instruction mnemonic in uppercase
switch (opcode) {
case "LOADN":
translateLoadN(tokens);
break;
case "LOADA":
translateLoadA(tokens);
break;
// Add cases for other instructions
default:
System.err.println("Error: Unknown opcode - " + opcode);
break;
}
}
private void translateLoadN(String[] tokens) {
if (tokens.length == 2) {
int num = Integer.parseInt(tokens[1]);
String binary = String.format("%8s", Integer.toBinaryString(num)).replace(' ', '0');
output.println("0000" + binary);
} else {
System.err.println("Error: Invalid LOADN instruction");
}
}
private void translateLoadA(String[] tokens) {
if (tokens.length == 2) {
int num = Integer.parseInt(tokens[1]);
String binary = String.format("%8s", Integer.toBinaryString(num)).replace(' ', '0');
output.println("0001" + binary);
} else {
System.err.println("Error: Invalid LOADA instruction");
}
}
从根本上来说,该代码正在丢弃有价值的信息。在进行确定操作码的工作后,该确定仅用于发出操作码本身,但不用于通知如何处理操作数。
通常,指令集架构具有格式,每种格式都有一定数量和类型的允许操作数 - 每条指令将采用其中一种格式的形式。
所以,你能做的是:
if ( opcode == "ADD" ) { emit ( "0000" ); format = Three_operand; } break;
...
switch ( format ) {
case Three_operand: ... break;
}
if ( opcode == "ADD" ) { emit ( "0000" ); handle3operands (); } break;
// nothing left to do here as common code is invoked by function call.