Assembly 8086 program
Solution 1
MOV AX,DATA
MOV DX,AX
This is wrong.
Correct answer is:
MOV AX,DATA
MOV DS,AX
we cant send data from memory to segment registers(DS) directly . so we are sending through General purpose registers(AX).
Solution 2
The algorithm searches a number in a list of numbers.
If it is found, CF
is set. If it is not found CF
is cleared.
INT 21H is the MS-DOS service interupt. Function 4Ch ends the program with an error code in AL (which contains the number to be found).
DATA SEGMENT
VALUES DB 1,2,3,4,5,6,7,8,9
ITEM DB 6
DATA ENDS
CODE SEGMENT
ASSUME CS:CODE,DS:DATA
START: MOV AX,DATA
MOV DX,AX
LEA SI,VALUES ; DS:SI points to the VALUES structure
MOV AL,ITEM
COMPARE: CMP AL,[SI] ; Compare with number in list
JZ Found ; Jump to Found if equal
INC SI ; Try next
LOOP COMPARE ;
CLC ; Clear CF (not found)
JMP EXIT ; Quit
Found: STC ; Set CF (found)
EXIT: MOV AH,4CH ; End program with error code AL = 6.
INT 21H
ENDS
CODE END
Solution 3
The LOOP
instruction is curious here. This instruction decrements CX
and jumps only if CX
is not zero. This means that the loop runs CX
times, but CX
is never set by the program.
CX
is likely zero on entry, and the first decrement will make it 65535, so it will actually loop a maximum of 65536 times, searching past the end of the list if the element is not found.
To make it correct, add MOV CX, ITEM - VALUES
before the loop start. Since ITEM
comes right after VALUES
, subtracting their addresses will give the number of bytes (elements) in the list.
Often a label is added to the end of a list to make such calculations more robust.
VALUES DB 1,2,3,4,5,6,7,8,9
VALUES_END LABEL BYTE
; ...
MOV CX, VALUES_END - VALUES
COMPARE: ; ...
LOOP COMPARE
Max
Updated on June 04, 2022Comments
-
Max almost 2 years
I am new to assembly language and this is some code that I didn't understand hoping that someone would help with it.
DATA SEGMENT VALUES DB 1,2,3,4,5,6,7,8,9 ITEM DB 6 DATA ENDS CODE SEGMENT ASSUME CS:CODE,DS:DATA START: MOV AX,DATA MOV DX,AX LEA SI,VALUES MOV AL,ITEM COMPARE: CMP AL,[SI] JZ Found INC SI LOOP COMPARE CLC JMP EXIT Found: STC EXIT: MOV AH,4CH INT 21H ENDS CODE END
This program is supposed to look for number
(6)
among1,2,3,4,5,6,7,8,9
I understand how it works in general but I have a few questions:
- Why did we use
CLC
andSTC
?? I know they putCF
into zero and one but why do we use it?? - Why did we use
MOV AH,4CH
in after theEXIT
label?? After the start label why did we say the following:
MOV AX,DATA
MOV DX,AX
Why didn't we just say:
MOV DX,DATA
Lastly, Could someone suggest a good book to learn assembly??
- Why did we use