Skip to content

Instantly share code, notes, and snippets.

@KyleGobel
Created March 4, 2023 05:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save KyleGobel/f93318f3f5fa137aa6d78c83bac10428 to your computer and use it in GitHub Desktop.
Save KyleGobel/f93318f3f5fa137aa6d78c83bac10428 to your computer and use it in GitHub Desktop.
using System.Text;
var RegFieldEncoding = new Dictionary<(int reg, int w), string>()
{
{ (0b000, 0), "al" },
{ (0b000, 1), "ax" },
{ (0b001, 0), "cl" },
{ (0b001, 1), "cx" },
{ (0b010, 0), "dl" },
{ (0b010, 1), "dx" },
{ (0b011, 0), "bl" },
{ (0b011, 1), "bx" },
{ (0b100, 0), "ah" },
{ (0b100, 1), "sp" },
{ (0b101, 0), "ch" },
{ (0b101, 1), "bp" },
{ (0b110, 0), "dh" },
{ (0b110, 1), "si" },
{ (0b111, 0), "bh" },
{ (0b111, 1), "di" },
};
//var filename = "listing_0037_single_register_mov";
var filename = args[0];
var decodedContents = new StringBuilder();
decodedContents.AppendLine("; ================================================");
decodedContents.AppendLine($"; {filename}");
decodedContents.AppendLine("; ================================================");
decodedContents.AppendLine();
decodedContents.AppendLine("bits 16");
decodedContents.AppendLine();
var asmBytes = await File.ReadAllBytesAsync(filename);
for (var i = 0; i < asmBytes.Length; i += 2)
{
ProcessInstruction(asmBytes[i..(i + 2)]);
}
Console.Write(decodedContents);
// End
void ProcessInstruction(byte[] bytes)
{
const byte MOV = 0b100010;
if (bytes[0] >> 2 == MOV)
{
// move the 7th bit to position 0 and check it
var d = bytes[0] >> 1 & 1;
var w = bytes[0] & 1;
var mod = bytes[1] >> 6;
switch (mod)
{
case 0b00: // memory mode, no displacement follows
break;
case 0b01: // memory mode, 8-bit displacement follows
break;
case 0b10: // memory mode, 16-bit displacement follows
break;
case 0b11: // register mode, no displacement
var reg = bytes[1] >> 3 & 0b111;
var rm = bytes[1] & 0b111;
var regField = RegFieldEncoding[(reg, w)];
var rmField = RegFieldEncoding[(rm, w)];
// if d == 1, swap the fields
if (d == 1)
{
(regField, rmField) = (rmField, regField);
}
decodedContents.AppendLine($"mov {rmField}, {regField}");
break;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment