user3554952
user3554952

Reputation: 1

Assembly language string reversal

For the input abcd, the output is dcbc but it should actually be dcba. So instead of a it is printing c.

It might be something stupid. Sorry. But I have wasted hours on this.

This is my code:

        .model small
        .stack 100h
        .data
        msg1 db 10,13,"enter the string:","$"
    maxlen db 100
    act_len db 0
    act_data db 100 dup('$')
    Newline db 13,10,"$"
    msg2 db 10 dup('$')

    .code
start:
    mov ax,@data
    mov ds,ax

    lea dx, msg1
    mov ah,09h
    int 21h

    mov ah,0ah
    lea dx, maxlen
    int 21h

    mov cl,act_len
    mov ch,0
    lea si,act_data
    add si,cx
    dec si
    dec cx
    lea di,msg2
rev:
    mov ax,[si]
    mov [di],ax
    inc di  
    dec si  
    dec cx

    jnz rev 

    mov ah,09h
    lea dx,Newline
    int 21h

    mov ah,09h
    lea dx,msg2
    int 21h


    mov ah,4ch
    int 21h

    end start

Upvotes: 0

Views: 145

Answers (1)

3yakuya
3yakuya

Reputation: 2672

Impossible for me to compile at the moment, but possible guilty one:

msg2 db 10 dup('$')
....

lea di,msg2
rev:
    mov ax,[si]
    mov [di],ax
    inc di  
    dec si  
    dec cx

You declare msg2 to be a row of bytes (or an array of bytes), but you load it with 16-bit ax, so you load prepared bytes with words, possibly overwriting. Would be better to use al, ah or other 8-bit register for this.

What's more, I am not sure if you will actually copy the first character because of this:

lea si,act_data
add si,cx
dec si
dec cx

You decrement cx at the start, so after 3rd iteration cx reaches 0 and there is no 4th iteration (jnz will not force jump because last operation resulted with 0 before the last necessary iteration). I believe you should not decrement cx before the loop starts.

Upvotes: 2

Related Questions