#include <iostream>
#include <fstream>
#include <vector>
#include <iterator>
#include <unordered_map>
unsigned char extractBits(unsigned char curr, int startBit, int endBit)
{
unsigned char mask = ((1 << (startBit - endBit + 1)) - 1) << endBit;
return (curr & mask) >> endBit;
}
struct instruction {
unsigned char opcode;
int direction;
int wordSize;
unsigned char mod;
unsigned char reg;
unsigned char rm;
};
instruction decodeInstruction(std::vector<unsigned char>& buffer, int byteIndex)
{
instruction decoded;
unsigned char currByte = buffer[byteIndex];
decoded.opcode = extractBits(currByte, 7, 2);
decoded.direction = extractBits(currByte, 1, 1);
decoded.wordSize = extractBits(currByte, 0, 0);
byteIndex++;
currByte = buffer[byteIndex];
decoded.mod = extractBits(currByte, 7, 6);
decoded.reg = extractBits(currByte, 5, 3);
decoded.rm = extractBits(currByte, 2, 0);
return decoded;
}
int main()
{
std::ifstream input;
input.open("many_reg.bin", std::ios::binary | std::ios::in);
std::vector<unsigned char> buffer((std::istreambuf_iterator<char>(input)), {});
input.close();
std::vector<instruction> all_instructions;
for(int i = 0; i < buffer.size(); i += 2)
{
instruction decoded = decodeInstruction(buffer, i);
all_instructions.push_back(decoded);
}
const unsigned char REG_OPCODE = 0b100010;
bool reg_dest = false;
std::unordered_map<unsigned char, std::string> reg_map =
{
{0b0000, "al"},
{0b0001, "ax"},
{0b0010, "cl"},
{0b0011, "cx"},
{0b0100, "dl"},
{0b0101, "dx"},
{0b0110, "bl"},
{0b0111, "bx"},
{0b1000, "ah"},
{0b1001, "sp"},
{0b1010, "ch"},
{0b1011, "bp"},
{0b1100, "dh"},
{0b1101, "si"},
{0b1110, "bh"},
{0b1111, "di"},
};
for(int i = 0; i < all_instructions.size(); ++i)
{
if(all_instructions[i].opcode == REG_OPCODE)
{
std::cout << "mov";
}
if(all_instructions[i].direction == 1)
{
reg_dest = true;
}
all_instructions[i].rm = (all_instructions[i].wordSize == 0 ? ((all_instructions[i].rm << 1) | 0) : ((all_instructions[i].rm << 1) | 1));
all_instructions[i].reg = (all_instructions[i].wordSize == 0 ? ((all_instructions[i].reg << 1) | 0) : ((all_instructions[i].reg << 1) | 1));
std::cout << " " << reg_map[all_instructions[i].rm];
std::cout << ", " << reg_map[all_instructions[i].reg];
std::cout << '\n';
}
return 0;
}