逐位减去两个数字

时间:2014-05-27 05:49:06

标签: assembly x86 masm

我在组装(MASM)中逐位减去2位数时遇到问题

这是我的算法代码

_Calculation:

    mov ecx , 7
    mov ebx, 0

_Subtract:
    ;clear out register for easy to check 
    xor eax, eax
    xor edx, edx

    ; al = bit i of first number
    mov al, first_num
    and al, 1h 

    ; dl = bit i of second number
    mov dl, second_num
    and dl, 1h

    ; save data for later use
    mov ah, al
    mov bh, dl

    ; bit i of difference = x xor y xor b
    xor al, dl
    xor al, bl
    or difference, al 

    ; b = ((not x) and y) or ((not x) and b) or (y and b)
    mov al, ah
    mov dl, bh
    not al
    mov dh, al ; copy not al in dh 
    and al, dl ; ((not x) and y)
    and dh, bl ; ((not x) and b)
    and dl, bl ; (y and b)
    or  al, dh ; ((not x) and y) or ((not x) and b)
    or  al, dl ; ((not x) and y) or ((not x) and b) or (y and b)
    mov bl, al

    ror difference, 1
    ror first_num, 1
    ror second_num, 1
    loop _Subtract
    ror difference, 1

当我测试运行时,大部分输入工作正常,但对于某些大数字,结果出错了

例如,当我取255 -1时差异为126而不是254

我写的代码有什么问题,有人可以提出建议吗?

也减去任何较小的数字到一个更大的数字不给出否定的结果,但数字127我不知道代码有什么问题。

提前谢谢

1 个答案:

答案 0 :(得分:0)

你不需要那样做

根据真相表:

A | B | A-B | Borrow
__________________
0 | 0 |  0  | 0
0 | 1 |  1  | 1
1 | 0 |  1  | 0
1 | 1 |  0  | 0

结果只是A和B的xor

所以你可以做xor ax, axxor eax, eax ......取决于操作数的大小