I'm writing a very small x86 assembler which currently outputs hex (or binary, it'd be trivial to change) machine code. How can I write this hex/binary into a file that I can actually execute?
For a simple input like:
mov ax, #1
ret
the assembler would output:
66b80100
c3
To append hex values to a binary in C++, you have to represent it as its raw int value and write that to the file.
Thus:
void writeHexStringToFile(string hex, ofstream& file) {
vector<string> hexBytes = hexBytesFromString(hex);
for (unsigned i = 0; i < hexBytes.size(); i++) {
istringstream buff(hexBytes.at(i));
int hexVal;
buff >> hex >> hexVal;
file.write(reinterpret_cast<char*>(&hexVal), sizeof(int));
}
}