这些天我一直在为 CHIP-8 制作汇编程序,今天我尝试实现参数以使操作码正常工作。但是,当我必须编写 2 个参数来完成操作码时,我有以下代码:
// Chip8Instruction is a struct I've made that holds the final machine code to be written, the mnemonic,
// the argument count and the position for each argument in hex
void writeTwoArguments(Chip8Instruction instruction, const std::string& line, int lineNum, const std::string& romName) {
unsigned int arg1;
unsigned int arg2;
std::string remainingLine = line;
std::string testStr;
std::stringstream stringStream;
// Arguments are comma and then space separated, assume I give 3, FF
std::string::size_type commaPos = line.find(',');
if (commaPos != std::string::npos) {
stringStream << std::hex << remainingLine.substr(0, commaPos); // This writes 3, like it should
testStr = stringStream.str(); // Holds "3", like it should
stringStream >> arg1; // This holds 0x3, like it should
stringStream.str("");
remainingLine.erase(0, commaPos+2); // FF remains, like it should
stringStream << std::hex << remainingLine;
testStr = stringStream.str(); // This holds nothing but it should have "FF", if I don't empty the stream it holds "3" from before
stringStream >> arg2; // This also holds nothing but it should have 0xFF, holds 0x3 if not empty stream
instruction.machineCode = instruction.start + (arg1 * instruction.arg1Pos) + (arg2 * instruction.arg2Pos);
}
writeMultipleDigitsToROM(romName, instruction.machineCode, lineNum);
}
最小可重现示例:
#include <iostream>
#include <sstream>
int main() {
std::string line = "3, FF";
std::stringstream stringStream;
unsigned int int1;
unsigned int int2;
// Get position of comma
std::string::size_type commaPos = line.find(',');
// Get everything up to the comma
stringStream << std::hex << line.substr(0, commaPos);
stringStream >> int1; // This holds 0x3, like it should
stringStream.str("");
line.erase(0, commaPos+2); // "FF" remains, like it should
stringStream << std::hex << line;
stringStream >> int2; // This is empty but should be 0xFF
}
正如代码注释所描述的,所持有的值要么是错误的,要么是过时的。可能是什么问题,为什么以及如何解决?
感谢所有帮助,谢谢!