首先,我对 8086 Assembly 非常陌生,掌握知识对我来说相当困难。尽管如此,我还是会尽力而为。
我一直在尝试编写一个代码来生成0-9范围内的随机数。在研究了几个例子和建议之后,这就是我的结论。为了简单起见,我没有对检索到的时钟计数应用任何数学函数,而且我认为这是不必要的。由于某些原因,我最终生成的某些数字(如 6,7)比 1,3 和 9 等数字少了几次。我相信这是因为我采用了时钟滴答的较低顺序,其中值发生了变化迅速。
我的目的是模拟掷骰子,稍后将以下代码的范围更改为 1-6。
我的问题是,这足以满足我的目的吗?或者有没有更好的方法来做到这一点?
codes:
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
; lets just take the lower bits of DL for a start..
MOV BH, 57 ; set limit to 57 (ASCII for 9)
MOV AH, DL
CMP AH, BH ; compare with value in DL,
JA RANDSTART ; if more, regenerate. if not, continue...
MOV BH, 49 ; set limit to 48 (ASCII FOR 0)
MOV AH, DL
CMP AH, BH ; compare with value in DL
JB RANDSTART ; if less, regenerate.
; if not, this is what we need
mov ah, 2h ; call interrupt to display a value in DL
int 21h
RET
@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
他做了什么:
1.我们将DX中的值转移到AX中
2.我们通关了DX。
3.我们12月10日搬到CX。
4.我们将 AX 除以 CX,因此我们得到 0-9 Dec 内的余数,该余数存储在 DX 中 5.最后,我们将 ASCII '0' (dec 48) 添加到 DX,将它们转换为 ASCII '0' 到 '9' 。