assembly - 8086随机数生成器(不仅仅是使用系统时间)?

标签 assembly random x86 x86-16 emu8086

我正在使用程序集 8086emu,我需要一个可生成 8 个数字的数字生成器。
我尝试使用 @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    

但仅当您生成一个数字时它才有用。重复调用会得到相同的数字,因为该时钟每秒仅滴答 18.2 次。

我尝试创建伪随机函数,但我对汇编还很陌生,但没有成功。 我想知道是否有一种方法可以在emu8086中执行类似于java的Math.random()函数的操作。

最佳答案

一个简单的伪随机数生成器将当前数字乘以 25173,然后加上 13849。该值现在成为新的随机数。
如果您像以前一样从系统计时器开始(这称为播种随机数生成器),这一系列数字对于简单任务来说将是足够随机的!

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

这实现了a Linear Congruential Generator (LCG) with a power-of-2 modulus%65536 是免费发生的,因为乘积 + 增量的低 16 位位于 AX 中,而高位则不然。

关于assembly - 8086随机数生成器(不仅仅是使用系统时间)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40698309/

相关文章:

assembly - 无法理解 Kip Irvine 的汇编语言书中的存储分配

delphi - 交换字变量的字节(低/高)的过程

c++ - 使用 __m64 引用将 C++ 项目转换为 x64

javascript - 在 OdinMonkey 中优化 asm.js

Python反复随机删除列表条目

python - random.choice 不是随机的

java - Random() 构造函数参数

gcc - 如何在 NASM 中导出符号

c - 菜鸟组装炸弹破坏 cmp 运算符(operator)

assembly - CMOS RAM 如何以一个字节存储年份