Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determining "Borrow" when subtracting binary numbers [closed]

Tags:

c#

binary-data

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?

like image 487
Bubo Avatar asked May 11 '26 14:05

Bubo


1 Answers

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.

like image 113
Theraot Avatar answered May 14 '26 03:05

Theraot