I am trying to write a chip8 emulator in C#. It will be necessary to simulate in software the operations that take place in hardware on the real chip.
There is an opcode that requires detecting a whether a borrow occurred during the subtraction of two binary numbers.
Byte1 - Byte2
Does anyone have any ideas as to how I can use C# to tell if a borrow occurred or not?
After searching in Wikipedia for the mysterious opcode you didn't mention, and looking for some implementations. I can conclude that the opcodes 8XY5 and 8XY7 (where X and Y are register identifiers) will do substractions.
For 8XY5 the register X will be set to the value of the register X minus the value of the register Y. And the register F will be set to 1 if the value of the register Y is greater or equal to the value of the register X (0 otherwise).
For 8XY7 the register X will be set to the value of the register Y minus the value of the register X. And the register F will be set to 1 if the value of the register X is greater or equal to the value of the register Y (0 otherwise).
This is the "pseudo"-code for 8XY5:
x = opcode[1]
y = opcode[2]
if (register[x] >= register[y])
register[0xF] = 1
else
register[0xF] = 0
result = register[x] - register[y]
if result < 0
result += 256
register[x] = result
and this is the "pseudo"-code for 8XY7:
x = opcode[1]
y = opcode[2]
if (register[y] >= register[x])
register[0xF] = 1
else
register[0xF] = 0
result = register[y] - register[x]
if result < 0
result += 256
register[x] = result
And here is a C# implementation:
const byte B_0 = 0x0;
const byte B_1 = 0x1;
const byte B_F = 0xF;
static void Main()
{
byte[] registers = new byte[16];
registers[0x1] = 255;
registers[0x2] = 127;
Opcode8XY5(registers, 1, 2);
Console.WriteLine(registers[0x1]);
Console.WriteLine(registers[0x2]);
Console.WriteLine(registers[0xF]);
Opcode8XY7(registers, 1, 2);
Console.WriteLine(registers[0x1]);
Console.WriteLine(registers[0x2]);
Console.WriteLine(registers[0xF]);
Console.ReadLine();
}
static void Opcode8XY5(byte[] registers, byte x, byte y)
{
registers[B_F] = registers[x] >= registers[y] ? B_1 : B_0;
registers[x] = (byte)(registers[x] - registers[y]);
}
static void Opcode8XY7(byte[] registers, byte x, byte y)
{
registers[B_F] = registers[y] >= registers[x] ? B_1 : B_0;
registers[x] = (byte)(registers[y] - registers[x]);
}
Check this implementation for reference.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With