Search code examples
assemblyx86

How to use LEA in 80x86 assembly?


I have this line of code in 80x86 assembly:

.DATA  
string BYTE 22 DUP  (?)   
.CODE  
input string,22  
lea EBX,string  

I want to compare the bytes of the string. How can I do this?


Solution

  • The LEA instruction is used to load an address into a register, and it can additionally also do some calculations, which are related to indexing an array.

    In your example you already loaded the address into EBX. Now you can access the characters of your string like this:

    mov al, byte ptr [ebx]
    

    However, if you just want to compare a string you should know that in x86 assembly there are instructions available which can compare a length of memory. In order to do this you load the maximum length in ECX, the first pointer into ESI and the second in EDI. Then you can use the cmps[x] (x being the operand size [b]yte, [w]ord or [d]word) in conjunction with the rep prefix to loop through the memory until you hit a byte matching matching the condition, or ecx becomes zero.

    An example:

     mov ecx, maxsize        ; maximum length of the memory that should be compared
     mov ebx, ecx
     lea esi, first_string   ; Pointer to first array to be compared
     lea edi, second_string  ; Pointer to second array to be compared
     repe cmpsb              ; Loop until either ecx is 0 or the bytes are different
     sub ebx, ecx            ; ebx will now have the number of bytes that matched.
    

    Note that the ecx is decreased, so if you want to know the length of the matching segment, you'd have to subtract the original length. if you just want to know if the strings were equal, then you can simply check if ecx is zero.

    If you want to do more complex checking you can still use these instructions without the rep prefix and still take advantage of the string instructions, because it also increases ESI

    For example:

        mov ecx, maxlen
        lea esi, string
    
     @@StringCmp:
        lodsb            ; Load the byte from DS:ESI to AL and increase ESI
    
        ; Byte is now in AL and you can do whatever you need with it.
    
        loop @@StringCmp