Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

8086 random number generator (not just using the system time)?

I am using assembly 8086emu and I need a numbers generator for 8 numbers.
I tried to use this piece of code by @johnfound:

RANDGEN:         ; generate a rand no using the system time

RANDSTART:
   MOV AH, 00h  ; interrupts to get system time        
   INT 1AH      ; CX:DX now hold number of clock ticks since midnight      

   mov  ax, dx
   xor  dx, dx
   mov  cx, 10    
   div  cx       ; here dx contains the remainder of the division - from 0 to 9

   add  dl, '0'  ; to ascii from '0' to '9'
   mov ah, 2h   ; call interrupt to display a value in DL
   int 21h    
RET    

but it is useful only when you generate one number. Repeated calls get the same number, because that clock only ticks 18.2 times per second.

I've tried to create pseudo-random function but I am pretty new to assembly and I did not succeed. I would like to know if there's a way to do something similar to java's Math.random() function in emu8086.

like image 895
Koren Minchev Avatar asked Jan 05 '23 01:01

Koren Minchev


1 Answers

One simple pseudo random number generator multiplies the current number by 25173, then adds 13849 to it. This value now becomes the new random number.
If you started from the system timer like you did (this is called seeding the random number generator), this series of numbers will be random enough for simple tasks!

MOV     AH, 00h   ; interrupt to get system timer in CX:DX 
INT     1AH
mov     [PRN], dx
call    CalcNew   ; -> AX is a random number
xor     dx, dx
mov     cx, 10    
div     cx        ; here dx contains the remainder - from 0 to 9
add     dl, '0'   ; to ascii from '0' to '9'
mov     ah, 02h   ; call interrupt to display a value in DL
int     21h    
call    CalcNew   ; -> AX is another random number
...
ret

; ----------------
; inputs: none  (modifies PRN seed variable)
; clobbers: DX.  returns: AX = next random number
CalcNew:
    mov     ax, 25173          ; LCG Multiplier
    mul     word ptr [PRN]     ; DX:AX = LCG multiplier * seed
    add     ax, 13849          ; Add LCG increment value
    ; Modulo 65536, AX = (multiplier*seed+increment) mod 65536
    mov     [PRN], ax          ; Update seed = return value
    ret

This implements a Linear Congruential Generator (LCG) with a power-of-2 modulus. %65536 happens for free because the low 16 bits of the product + increment are in AX, and the higher bits aren't.

like image 52
Sep Roland Avatar answered Jan 13 '23 11:01

Sep Roland