在汇编x86中逐位减去两个8位整数

时间:2013-06-25 20:15:12

标签: algorithm assembly x86 bit-manipulation cpu-registers

所以我试图实现这个算法来计算两个8位整数的差值

b = 0
difference = 0
for i = 0 to (n-1)

    x = bit i of X
    y = bit i of Y
    bit i of difference = x xor y xor b
    b = ((not x) and y) or ((not x) and b) or (y and b)

end for loop

这就是我所做的

calculation:
mov ebx, 0
mov diff, 0
mov ecx, 7

subtract:
    mov al, X
    and al, 1h ; find bit i of X
    mov dl, Y
    and dl, 1h ; find bit i of Y
    mov ah, al
    mov dh, al
    xor al, dl
    xor al, bl
    mov diff, al ; find bit i of the difference

    ; calculate b value for the next interation
    not ah
    and ah, dl
    not dh
    and dh, dl
    and dl, bl
    or ah, dh
    or ah, dl
    mov bl, ah

    ; rotate X and Y to get ready for the next iteration
    rol X, 1 
    rol Y, 1
    loop subtract

此代码的问题是它在循环的第一次迭代中唯一的工作

因此,例如,如果我输入第一个数字为2,第二个数字为1

当我经历循环,第一次迭代时,x值为0,y值为1,差值的i位为1,b值为1 ,但这只适用于第一次迭代,在下一次迭代中,我有x = 0,y = 0和b = 1(从上次计算),所以我希望我的差异为1,我的b值为此迭代为1,而我两个都得到0。

为什么代码不起作用,因为我遵循算法,并相应地实现。

提前谢谢

1 个答案:

答案 0 :(得分:2)

首先尝试使用更高级别的语言来理解算法,然后将其移植到asm。

#include <stdio.h>


//b = 0
//difference = 0
//for i = 0 to (n-1)
//
//    x = bit i of X
//    y = bit i of Y
//    bit i of difference = x xor y xor b
//    b = ((not x) and y) or ((not x) and b) or (y and b)
//
//end for loop


int main ( void )
{
    unsigned char X,Y,Z;

    unsigned char x,y,z,b,bnext;

    unsigned char i;

    X=0Xf5; Y=0Xf1;

    b=0;
    Z=0;
    for (i=1;i;i<<=1)
    {
        x=0;
        y=0;
        if(i&X) x=1;
        if(i&Y) y=1;
        z=((x^y)^b)&1;
        if(z) Z|=i;
        bnext = ((~x)&y) | ((~x)&b) | (y&b);
        b=bnext&1;
    }
    printf("0x%02X 0x%02X\n",Z,X-Y);




    return(0);


}

你甚至可能会重写几次以接近真实的指示。

   z=((x^y)^b)&1;

变为

   z = x;
   z = z ^ y;
   z = z ^ b;
   z = z & 1;