汇编的常见操作

#include <stdio.h>
#include <windows.h>

int sal_asm(int x,int y)
{
    __asm{
        mov eax,x;
        mov cl,byte ptr y;
        sal eax,cl;
    }
}

int shl_asm(int x,int y)
{
    __asm{
       mov eax,x;
       mov cl,byte ptr y;
       shl eax,cl;
    }
}


void strncpy_asm(char *dst ,char *src ,size_t len)
{
    __asm{
        mov edi,[ebp+8];
        mov esi,[ebp+0xc];
        mov ecx,[ebp+0x10];
        cld; 设置DF = 0,ESI,EDI++
        rep movs byte ptr[edi],byte ptr[esi];
    }
}

unsigned int strlen_asm(char *s)
{
    __asm{
        xor eax,eax;
        xor ebx,ebx;
        mov esi,s;
L0:
        lodsb; 把[esi]种的一个字节放到al中,esi++
        cld;
        test al,al; 判断esi是否已经指向字符串s的''
        jz L1;
        INC ebx;
        jmp L0;
L1:
        mov eax,ebx
    }
}

int strncmp_asm(const char *s1,const char *s2,size_t len)
{
    __asm{
        mov ecx,len;
        mov esi,s1;
        mov edi,s2;
        repz cmpsb; 当ecx不为零并且zf =1
        jecxz L1; ecx为0,前len个字节比较完毕
        js L2;
        jns L2;
L1:
        js L2; 最后一个字符不相等
        jns L2; 最后一个字符不相等
        xor eax,eax; 最后一个字符串相等
        jmp L4;
L2:
        xor eax,eax;
        xor ebx,ebx;
        mov al, byte ptr[esi-1];
        mov bl, byte ptr[edi-1];
        sub eax,ebx;
        jmp L4
L4:

    }
}

int strcmp_asm(const char *s1,const char *s2)
{
    __asm{
        xor eax,eax;
        mov esi,s1;
        mov edi,s2;
L2:
        lodsb;
        scasb;
        jne L1;
        test al,al;判断是否为''
        jne L2;
        xor eax,eax;
        jmp L3;
L1:
        xor ebx,ebx;
        mov bl,byte ptr[edi-1];
        sub eax,ebx; 不相等字符做差返回
L3:

    }
}

int main()
{
    char buf[128] = {0};
    char *str = "hello";
    char *str1 = "hello";
    int len = 0;
    
    len = strlen_asm(str);
    strncpy_asm(buf,str,len);
    printf("strncpy_asm buf: %s and len : %d
",buf,len);
    printf ("shl_asm :10 << 5 = %d 
",shl_asm(10,5));
    printf ("sal_asm :10 << 5 = %d 
",sal_asm(10,5));
    printf("s1 %s s2 
",strncmp_asm(str,str1,8)==0?"==":"!=");
    printf("s1 %s s2 
",strcmp_asm(str,str1)==0?"==":"!=");
    system("pause");
    
    return 0;
}
原文地址:https://www.cnblogs.com/persuit/p/7658942.html