简体   繁体   中英

How to compare two strings in assembly?

I'm new in assembly. I want to compare two string using "cmps". I read some examples and I write this :

GETSTR MACRO STR
   MOV AH,0AH
   LEA DX,STR
   INT 21H
ENDM

PRINTSTR MACRO STR
   MOV AH,09H
   LEA DX,STR
   INT 21H
ENDM


EXTRA SEGMENT
   DEST DB ?
EXTRA ENDS

DATA SEGMENT
    SOURCE DB ?
    STR1 DB 0AH,0DH,'ENTER STR  : ' ,'$'
    ENTER DB 10,13,'$'
    SAME  DB 0AH,0DH,'TWO STR ARE THE SAME   ' ,'$'
    NSAME DB 0AH,0DH,'TWO STR ARE NOT THE SAME   ' ,'$'

     USER  DB 6,10 DUP('$')
     USER1 DB 6,10 DUP('$')
DATA ENDS

CODE SEGMENT
ASSUME DS:DATA,CS:CODE,ES:EXTRA
START:
    MOV AX,DATA
    MOV DS,AX
    MOV AX,EXTRA
    MOV ES,AX

    PRINTSTR STR1
    GETSTR USER1

    PRINTSTR STR1
    GETSTR USER

    LEA BX,USER
    MOV SI,BX

    LEA BX,USER1
    MOV DI,BX

    CLD
    MOV CX,5
REPE CMPSB
    JCXZ MTCH
    PRINTSTR NSAME
    JMP ENDPR

MTCH:   
    PRINTSTR SAME
ENDPR:
    MOV AH,4CH
    INT 21H

 CODE ENDS
 END START

I have some question:

  1. what is exactly the numbers 6,10 in the code below :

     USER DB 6,10 DUP('$') 
  2. Is there any mistake with the Macros?

  3. Is it necessary to declare EXTRA SEGMENT ?
  4. For any similar strings input the output is : "they are not the same?" what is the reason?
  1. The number 6 defines the number of characters plus 1 that you want DOS to input. The number 10 defines the length of the buffer that follows. Actually the number 7 would have been enough!
  2. The macros seem fine.
  3. You don't need the EXTRA segment. Moreover putting it into ES is wrong because both strings that you will be comparing are in the DATA segment.
    Also both LEA instructions must fetch an address that is 2 higher. The first byte will still be the maximum number of bytes to read (6) and the second byte will be the number of bytes actually read [0,5]
  4. The comparison you're making indifferably uses 5 characters. If you don't take into account the real number of characters as reported by DOS in the second byte it's no wonder results might not be satisfying.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM