[Math] What actually determines a ‘borrow’ in binary subtraction

binarybinary operations

Given Byte1 and Byte2 in binary. How to determine whether Byte1 - Byte2 results in a borrow or not?

I've seen 10 different ways:

  1. Iterate over the bits in Byte1 and Byte2 in parallel, if we ever
    come across a bit in Byte2 that is greater than its equivalent bit
    in Byte1, we have a borrow.
  2. If 'Byte1 < Byte2` we have a borrow

I'm asking because I'm writing a CHIP-8 interpreter. One of the opcodes is 8XY5: Register Y is subtracted from Register X. Register F is set to 0 when there's a borrow, and 1 when there isn't

I've seen implementations that did the second approach:

if(Register[X] < Register[Y]) 
    Register[0xF] = 0; // there is a borrow
else 
    Register[0xF] = 1;                  
Register[X] -= Register[Y];

That doesn't really make sense to me. Take 5 and 3 in binary for example:

0101 -
0011
----
0010

According to their approach, there is no borrow, but we can clearly see that there's a borrow happening in the second bit (0 – 1)

I'm confused. Any help would be appreciated!

Best Answer

This is definitely confusing language. What they intend to mean is whether there is ultimately a borrow from beyond the highest-order bit. The point is to tell whether the difference of two positive numbers is negative, and then paired with the skip instruction you can do conditional jumps ("if x < y { ... }"). One way to think about it is extend the first number with an initial zero bit:

0|0011 -
 |0101
------
1|1110

That first 1 reflects the "borrow."