How to seed a random number generator in an assembly?

I try to create a complete random number in the assembly, but every time I run the program, it gives me the same numbers in the same order. If the numbers are 12, 132, 4113 or something else, they will be repeated every time the code is run.

The program I'm trying to do is like a guessing game.

    IDEAL
MODEL small
STACK 100h
DATASEG
;vars here
RNG_Seed dw ? 

CODESEG
; Generates a pseudo-random 15-bit number.
; Parameters: <none>
; Clobbers:   AX, DX
; Returns:    AX contains the random number
proc GenerateRandNum
   push bx
   push cx
   push si
   push di


   ; 32-bit multiplication in 16-bit mode (DX:AX * CX:BX == SI:DI)
   mov  ax, [RNG_Seed]
   xor  dx, dx
   mov  cx, 041C6h
   mov  bx, 04E6Dh
   xor  di, di
   push ax
   mul  bx
   mov  si, dx
   xchg di, ax
   mul  bx
   add  si, ax
   pop  ax
   mul  cx
   add  si, ax


   ; Do addition
   add  di, 3039h
   adc  si, 0


   ; Save seed
   mov [RNG_Seed], di


   ; Get result and mask bits
   mov  ax, si
   and  ah, 07Fh


   pop  di
   pop  si
   pop  cx
   pop  bx
   ret
endp GenerateRandNum

What can I do to run different random numbers every time?

+4
source share
1 answer

You need to initialize RNG_Seedwith something "random." And this is actually a bit problematic on a deterministic machine such as a computer.

, , , , HW , .

, , .

, ( 16b), BIOS - :

xor ah,ah  ; ah = 0
int 1Ah    ; returns in cx:dx ticks since midnight (18.2Hz ticks)
; let mix the cx:dx a bit together to get a bit more entropy out of it
rol cx,8
xor dx,cx
xor [RNG_Seed],dx ; "add" that entropy to the original seed

, ( ), "" :

, , ( 3 ) , inc counter , 4 (3 + = 4 * 4 = 16 ). (xor) RNG_Seed.

RNG ( , , ).


EDIT: , , , add, xor. , BIOS , xor - (, , BTW, exe-), , 4: 4: 4: 4 ( xor, , 16b), xor . BIOS, xor .

4: 4: 4: 4 , 16b , xor-ed . , , int 16h, ah=1, , , , 16 ( , ), 4 , [] . , 16b , (.. - 10000-13000 → 2 , 8 ). , 4 , , 16b. , , . , , , , , , . , ( ~ 20 , dosbox DOS).

+4

Source: https://habr.com/ru/post/1683341/


All Articles