jayed bin zakir
jayed bin zakir

Reputation: 11

Take string length and reverse in 8086 emulator

Can anyone help me to reverse this string?

Here is my code

include 'emu8086.inc'    

 PRINTN 'Enter length of string'
 mov ah,1h
 int 21h

 printn                 
 
 print "Enter String here: "
 mov cl,al
 sub cl,'0'         
 mov dl,cl           
 mov bx,0
 
 
 p1:  
 
 mov ah,1h
 int 21h             
 
 mov [bx],ax        
 inc bx             
 dec cl
 cmp cl,0           
 jne p1       
 
 
 printn
 PRINT 'inputted string : '
 
 mov cl,dl
 mov bx,0

 output:
 mov dl,[bx]
 
 mov ah,2h
 int 21h    
 
 inc bx   
 dec cl
 cmp cl,0  
 jne output
 printn     
 
 mov ax, 4c00h  
 int 21h

ret

Upvotes: 1

Views: 633

Answers (1)

Sep Roland
Sep Roland

Reputation: 39316

  • You are storing the string at address 0 (mov bx, 0). Depending on the kind of program you create, this could overwrite important data. In below example program, I chose the .COM format where you don't have to concern yourself about setting up the segment registers. They're all equal to each other.
  • When you store a string character (mov [bx],ax), you should use AL. The character is only in the AL register.
  • In the sequence dec cl cmp cl,0 jne p1, the cmp cl, 0 is redundant since the dec cl instruction already provides the tested for zero flag ZF. And knowing that this is an input loop with a DOS system call, so it's slow anyway, you could just use loop p1.
  • The message 'inputted string : ' does not truly reflect what you do, does it? Maybe write something like 'reversed string : '?
  • Like @Peter Cordes told you in a comment, at the end of the p1 input loop, the BX register is pointing past the last character of the string. Re-use it, but do so in a pre-decrementing way. That's the opposite of the post-incrementing way that you used in the input loop.
  • The output loop can also use the smaller loop p2 instruction because speedwise the bottleneck is the DOS system call which is slow anyway.
#make_COM#
include 'emu8086.inc'
ORG 100h

  PRINTN 'Enter length of string'
  mov  ah, 01h
  int  21h                  ; -> AL = "0" to "9"
  sub  al, '0'
  mov  dl, al
  mov  dh, 0                ; -> DX = 0 to 9
  printn

  print "Enter String here: "
  mov  bx, OFFSET Buffer
  mov  cx, dx
p1:  
  mov  ah, 01h
  int  21h
  mov  [bx], al
  inc  bx                   ; "post-increment"
  loop p1
  printn

  PRINT 'reversed string : '
  mov  cx, dx
p2:
  dec  bx                   ; "pre-decrement"
  mov  dl, [bx]
  mov  ah, 02h
  int  21h    
  loop p2
  printn

  mov ax, 4C00h
  int 21h

Buffer db 10 dup(0)

Upvotes: 1

Related Questions