Error while reversing string in 8086

自作多情 提交于 2019-12-13 21:19:57

问题


I have this code to reverse a string using 8086 ALP. But the code does not work as intended and gets into a infinite loop or prints some random charecter.

.model small
.stack 100h
.data
String1 DB "Assembly Language Program$"
Length dw $-String1-1

.code
Main proc
MOV AX, @data
MOV DS, AX

MOV SI, Offset String1
MOV CX, Length  
ADD SI, CX

Back: MOV DL, [SI]
MOV AH, 02H
INT 21H
DEC SI
LOOP Back  

MOV AH, 4CH
INT 21H
Main endp
End main

回答1:


You code has 2 issues:

  1. $ stands for "the offset of the current compiling instruction", and it can be used in some offset arithmetic, but the way you are declaring your length data is not doing what you think. Actually, length is containing the offset of itself, minus the offset of String1, minus 1. The common way to use $ to compute a length is by using an equ constant right after the string declaration, like:

    String1 DB "Assembly Language Program$"
    Length EQU $-String1 
    

    That is, the MOV CX, Length will load CX with the length of the string and not a memory offset. An EQU does not take any place in the resulting program. If anyway you would like to have a place in memory with the string length and not only defining it at assembly time, you can do

    String1 DB "Assembly Language Program$"
    strl EQU $-String1 
    Length DW strl    ;the initialized data will be the string length, not an offset
    
  2. your code start to reverse the string 1 byte too long, as for a 1 byte string you don't have to add anything, so e.g a DEC SI will correct the offset.

The following (slightly) modified program do what you want:

.model small
.stack 100h
.data
String1 DB "Assembly Language Program$"
Length equ $-String1-1

.code
Main proc  
MOV AX, @data
MOV DS, AX

MOV SI, Offset String1
MOV CX, Length  
ADD SI, CX
DEC SI

Back: MOV DL, [SI]
MOV AH, 02H
INT 21H
DEC SI
LOOP Back  

MOV AH, 4CH
INT 21H
Main endp
End main



回答2:


I think that the problem is

ADD SI, CX

whereas you have to

MOV SI, CX

I would like to say that i am not familiar with this kind of implementation and i cannot help more. But take a look to this code which is also reverse a String.

TITLE reverse
ASSUME CS:CODE, DS:data
CODE SEGMENT


START:
    MOV AX,data
    MOV DS,AX

    MOV SI,0 ; pointer
LENGTH:
    CMP message[SI],'$'
    JE NEXT

    INC SI
    JMP LENGTH
NEXT:
    MOV CX,SI
    DEC SI
CHANGE:
    MOV DL,message[SI]

    MOV AH,02H  
    INT 21H     

    DEC SI
    LOOP CHANGE
END:
    MOV AH,4CH 
        int 21h 


CODE ENDS

DATA SEGMENT 

    MSG DB 10,13,"$"
    message DB 'Assembly Language Program$'

DATA ENDS

END START


来源:https://stackoverflow.com/questions/20949662/error-while-reversing-string-in-8086

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!