I
I
impressive172021-04-25 18:05:01
Electronics
impressive17, 2021-04-25 18:05:01

How to implement subtraction with a loan?

Tell me how to implement borrowed subtraction using the SUB [src,] dst command, branch by carry command, and subtract one.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim Evdokimov, 2021-05-30
@4el_C_Foruma

This instruction can be used to subtract 64-bit numbers on 32-bit processors, or 32-bit numbers on 16-bit processors.
In the first case, you can use pairs of registers EDX:EAX and EBX:ECX, and in the second DX:AX and BX:CX. If a borrow occurs when subtracting values ​​in lower registers, then it will be taken into account when subtracting higher words.
Example:
.model tiny
.code
ORG 100h
start:
MOV DX, 1 ;In DX:AX pair (0001:0000)
MOV AX, 0 ;32-bit number 65536
MOV BX, 0 ;In BX:CX pair
MOV CX, 1 ;32-bit number 1
;65536 - 1 = 65535, i.e. after subtracting
;DX:AX = 65535 (0000:FFFF)
SUB AX, CX ;AX = FFFF
SBB DX, BX ;DX = 0000
RET
END start
In this example, we use 16-bit registers to perform a 32-bit subtraction operation.
In the DX:AX register pair, we will have the number 65536 (00010000h), which does not fit in one 16-bit register.
We subtract the number 1 from this number. This number can be subtracted as an immediate value, but to understand that any other 32-bit number can be subtracted, we will place a one in the BX:CX register pair (the number will be 00000001h).
Then, first, we subtract the low register of the second number from the low register of the first number using the SUB instruction. The result will be equal to FFFF, since we subtract one from zero, and the CF flag will be set.
Then, using the SBB command, we subtract the senior register of the second number from the high register of the first number (we subtract zero from one). If we used the SUB instruction, then we would get 1 in the DX register. That is, the DX:AX pair would contain the 32-bit number 1FFFFh (131071 in decimal):
65536 - 1 = 131071
, which, of course, is wrong.
But we use the SBB command, which, in addition to subtracting the BX value from DX in our example, also subtracts the value of the carry flag (which in our example is 1) from the result. As a result, we get the correct value DX:AX = 0000:FFFF = 65535.
And finally, as always, about the origin of the abbreviation SBB.
SBB is SuBtract with Borrow - subtraction with borrowing.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question