Chapter 5
Procedures
Assembly Language Programming Exercise
Problem # 5:
The RandomRange procedure from the Irvine32 library generates a pseudorandom integer between 0 and N 1. Your task is to create an improved version that generates an integer between M and N 1. Let the caller pass M in EBX and N in EAX. If we call the procedure BetterRandomRange, the following code is a sample test:
mov ebx,-300 ; lower bound
mov eax,100 ; upper bound
call BetterRandomRange
Write a short test program that calls BetterRandomRange from a loop that repeats 50 times. Display each randomly generated value.
Solution:
INCLUDE Irvine32.inc
.data
.code
main PROC
call Clrscr
mov eax, -300
mov ebx, 100
mov ecx, 50
L1:
push eax ; doesn't change range
push ebx
call BetterRandomRange
pop ebx
pop eax
Loop L1
call WaitMsg
exit
main ENDP
BetterRandomRange PROC
sub ebx, eax ;mov 400 to ebx
xchg ebx, eax ;random works with eax
call RandomRange ; generate random int
neg ebx
sub eax, ebx ;sub 300 from eax to define range
call WriteInt ; write signed decimal
call Crlf
ret
BetterRandomRange ENDP
END main
.data
.code
main PROC
call Clrscr
mov eax, -300
mov ebx, 100
mov ecx, 50
L1:
push eax ; doesn't change range
push ebx
call BetterRandomRange
pop ebx
pop eax
Loop L1
call WaitMsg
exit
main ENDP
BetterRandomRange PROC
sub ebx, eax ;mov 400 to ebx
xchg ebx, eax ;random works with eax
call RandomRange ; generate random int
neg ebx
sub eax, ebx ;sub 300 from eax to define range
call WriteInt ; write signed decimal
call Crlf
ret
BetterRandomRange ENDP
END main
Let me know in the comment section if you have any question.
Previous Post:
Program to Simple Addition (2) in Assembly Language using Visual Studio