Random
PRNG
This is a simple Pseudo-Random Number Generator I wrote. It is very simple, and use the same algorithm as most other PRNG's in high level languages - Linear congruential generator.
The following code is written to be used in a library. To learn how to create and use a library,
take a look here.
rand.asm
;---------------------------------------------------------------
%TITLE "rand.asm"
;---------------------------------------------------------------
IDEAL
MODEL small
;---------------------------------------------------------------
DATASEG
;---------------------------------------------------------------
magic_no_1 DD 1103515245
magic_no_2 DW 12345
;---------------------------------------------------------------
UDATASEG
;---------------------------------------------------------------
dd_result DD ?
rand_seed DW ?
;---------------------------------------------------------------
CODESEG
;---------------------------------------------------------------
PUBLIC seed_random, get_random
PUBLIC magic_no_1, magic_no_2
;---------------------------------------------------------------
;
; SEED_RANDOM
;
; return: seed in dx and rand_seed
;
;---------------------------------------------------------------
PROC seed_random
push bx ; save registers
push cx
push dx
@@L10:
mov ah, 2Ch ; get ticks
int 21h ;
or dx, dx ; make sure it's not zero
jz @@L10
mov [rand_seed], dx ; copy seed to global var
pop dx ; restore registers
pop cx
pop bx
@@L99:
ret
ENDP seed_random
;---------------------------------------------------------------
;
; GET_RANDOM
;
; x = (xa + c) mod 32767
;
; expect: bx = max
; cx = min
;
; return: ax = result
; rand_seed = new value between 0 and 32767
;
;---------------------------------------------------------------
PROC get_random
push cx ; save registers
push bx
@@L10:
mov ax, [word magic_no_1 + 2] ; copy high word
mov bx, [rand_seed]
mul bx ; result in dx:ax
mov [word dd_result + 2], dx ; high word of result
mov [word dd_result], ax ; copy low word
mov ax, [word magic_no_1] ; copy low word
mov bx, [rand_seed]
mul bx ; result in dx:ax
; - don't use dx
add ax, [magic_no_2] ; + c
and ax, 7FFFh ; mod 32767
or ax, ax ;
jnz @@L20 ;
call seed_random ; if zero, get new seed
jmp @@L10 ; and start again
@@L20:
mov [rand_seed], ax ; make new seed
@@L99:
ret
ENDP get_random
END