How to compare two strings in x86 assembly with FASM?

Viewed 768

I want to compare the user input stored in the register si with another string.
By the way, I'm using FASM. Here's my code so far after the user input.
If I'm using the repe cmpsb command, I know that I have to use the extra segment, but I don't know how. And the repe cmpsb command doesn't work with this code.

.input_done:
   cmp si, 0
   je no_input
   jmp short .compare_input


.compare_input:
    mov cx, 20 ;For the repe cmpsb command.
    cld
    mov di, info ;The string I want to compare.
    mov es, di
    mov di, info
    repe cmpsb
    cmp cx, 0
    je showinfo
.showinfo:
    ... ;The output string if both string are the same.

info db "info", 0
1 Answers
mov di, info ;The string I want to compare.
mov es, di

For a simple program it's probably true that both strings will be stored in the same memory segment. Just place the value from DS in ES.

...
push ds
pop  es
mov  di, info
...

And the repe cmpsb command doesn't work with this code.

You've set the counter CX to a fixed number of 20, where at least one of the strings ("info") has only 4 characters. No wonder that the comparison fails.


Since you want to compare for equality, your first step will be to see if both strings have the same lengths. If not, you already know the answer.
If they are the same length, then use that as the counter CX.

; String1 pointer in DS:SI, length in CX
; String2 pointer in ES:DI, length in DX

cmp  cx, dx
jne  NotEqual
repe cmpsb
jne  NotEqual
Equal:       ; .showinfo:
...          ; The output string if both string are the same.
; Don't fall through here!!!
NotEqual:
...
Related