问题
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:
$
stands for "the offset of the current compiling instruction", and it can be used in some offset arithmetic, but the way you are declaring yourlength
data is not doing what you think. Actually,length
is containing the offset of itself, minus the offset ofString1
, minus 1. The common way to use$
to compute a length is by using anequ
constant right after the string declaration, like:String1 DB "Assembly Language Program$" Length EQU $-String1
That is, the
MOV CX, Length
will loadCX
with the length of the string and not a memory offset. AnEQU
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 doString1 DB "Assembly Language Program$" strl EQU $-String1 Length DW strl ;the initialized data will be the string length, not an offset
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