For my coursework, I have to write a program that copies all the values lower than 1000h from an array of signed 16-bit numbers (called inputArray) to another array (called outputArray). In this exercise, I'm required to use the string instructions lods and stos.
Let's look at all the key elements of your task in relation to the program code that you received/found (I think).
.lower and signed
Because the numbers involved are signed numbers, you need to use the appropriate conditional instructions. These include jl
(JumpIfLess) and jg
(JumpIfGreater). The example program used ja
(JumpIfAbove) which suits working with unsigned numbers!
.1000h
Simply change the line value equ 8000h
.
.another array
The example program stores the results on top of the original numbers. For your task you need to define a 2nd array. This additional array must be able to accomodate at most the same number of elements as the input array did:
inputArray dw 8933h, 1240h, 0328h, 99A0h, 0F422h, 0101h
outputArray dw 0, 0, 0, 0, 0, 0
Rather than writing it like above you can use the dup
operator:
inputArray dw 8933h, 1240h, 0328h, 99A0h, 0F422h, 0101h
outputArray dw 6 dup (0)
.lods and stos
The program you got already uses these instructions.
Let's write a better example program (keeping that silly detour via the stack).
.If you put the data section below the code section, you don't need that jmp init
anymore.
.Make the labels stand out by indenting the code.
.Have the operands aligned as well.
.Avoid jumping around. Don't ja insert
but rather jna nextElem
and put the insertion instructions close by.
.Avoid the slow loop
instruction. dec cx
jnz ...
replace it nicely. You can even use another counting register altogether (*).
org 100h
value equ 8000h
lea SI, numbers
mov CX, (init-numbers)/2
mov DX, 0h
cld
compare:
lodsw
cmp AX, value
jna nextElem
push AX ;insert
inc DX ;insert
nextElem:
dec cx
jnz compare
lea DI, numbers
;No need to setup CX, just use DX (*)
extract:
pop AX
stosw
dec dx ;(*)
jnz extract
end:
int 20h
numbers dw 8933h, 1240h, 0328h, 99A0h, 0F422h, 0101h
How this should be written.
org 100h
mov si, offset inputArray
mov di, offset outputArray
cld
Again:
lodsw
cmp ax, 1000h
jnl IsNotLess
stosw
IsNotLess:
cmp si, offset outputArray ;Arrays must be adjacent for this to work!
jb Again
int 20h
inputArray dw 8933h, 1240h, 0328h, 99A0h, 0F422h, 0101h
outputArray dw 6 dup (0)
The output array will have 5 elements:
- The negative number 8933h
- The positive but smaller than 1000h number 0328h
- The negative number 99A0h
- The negative number 0F422h
- The positive but smaller than 1000h number 0101h