Search code examples
assemblymasmx86-168085

8086 masm program for palindrome checking


.code
> 
>     start:
>     mov ax,03h
>     int 10h
>     mov ax,seg msg1
>     mov ds,ax
>     mov dx,offset msg1
>     mov ah,09h
>     int 21h
>     mov si,offset str
>     read:
>     mov ah,01h
>     int 21h
>     cmp al,0dh
>     je next
>     mov [si],al
>     inc si
>     inc count
>     jmp read
>     next:
>     mov di,offset str
>     mov al,count
>     mov cl,al
>     mov ch,00h
>     dec si
>     check:
>     mov al,[si]
>     cmp al,[di]
>     jne nt
>     dec si
>     inc di
>     loop check
>     mov ax,seg msg2
>     mov ah,09h
>     int 21h
>     jmp exit
>     nt:
>     mov ax,seg msg3
>     mov ds,ax
>     mov dx,offset msg3
>     mov ah,09h
>     int 21h
>     exit:
>     mov ax,4c00h
>     int 21h
>     END start

This is part of 8086 masm code for checking whether a string is a palindrome or not.msg1 is 'Enter string',msg2 is 'string is palindrome',msg3 is 'string is not palinrome' What does 'cmp al,0dh' performs in this code?


Solution

  • It's not mentioned where this code came from, but it's incomplete (e.g. as Mario points out: no next: label) present. But we can piece it together:

    .code
    
    start:
        mov ax,03h           ; Get cursor position and shape
        int 10h
    
        ; Display a message to the user
        ; (NOTE: we only know it's in "msg1" but don't know the contents
        ;
        mov ax,seg msg1      ; DS:DX to point to msg1
        mov ds,ax
        mov dx,offset msg1
    
        mov ah,09h           ; Write the string (pointed by DS:DX) to stdout
        int 21h
    
        mov si,offset str    ; Get the the destination string location, DS:SI
    
        ; Read a string in from the user, terminated by new line (0dh)
        ;
    read:
        mov ah,01h           ; Read a character
        int 21h
    
        cmp al,0dh           ; if it's a line feed, then go to "next"
        je next
    
    
        mov [si],al          ; otherwise, store the char in "str" and get the next one
        inc si
        inc count            ; increment character count
        jmp read
    
        ; Below is where the actual code to compute a palindrome starts
    next:
        mov di,offset str
        mov al,count
        mov cl,al
        mov ch,00h
        dec si
    check:
        mov al,[si]
        cmp al,[di]
        jne nt
        dec si
        inc di
        loop check
    
        mov ax,seg msg2
    

    So all this code does is display a message to the user prompting them to enter a string, terminated by a line feed (0dh) and it reads the string in (to location str). It also provides the number of characters read in count. Where str, count, and msg1 are defined aren't given.