作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在使用程序集 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/
我是一名优秀的程序员,十分优秀!