使用Irvine汇编随机数

时间:2012-05-07 01:01:36

标签: assembly random numbers masm irvine32

当我实现在Assembly中为我们提供的随机数生成器过程时,一半时间它给我一个除零错误,另一半时间它完美地工作。我相信我正在正确地实现代码,但会为您提供如何编写代码。

randomCompNum PROC
    call Randomize               ;Sets seed
    mov  eax,10                  ;Keeps the range 0 - 9

    call RandomRange
    mov  compNum1,eax            ;First random number

L1: call RandomRange
    .IF eax == compNum1          ;Checks if the second number is the same as the first
        jmp L1                   ;If it is, repeat call
    .ENDIF
     mov compNum2,eax            ;Second random number

L2: call RandomRange
    .IF eax == compNum1          ;Checks if the third number is the same as the first
        jmp L2                   ;If it is, repeat
    .ELSEIF eax == compNum1      ;Checks if the third number is the same as the second
        jmp L2                   ;If it is, repeat
    .ENDIF
    mov compNum3,eax             ;Third random number stored

    ret

randomCompNum ENDP

以下是Visual Studios为我提供的RandomRange的反汇编

_RandomRange@0:
004019C1  push         ebx  
004019C2  push         edx  
004019C3  mov          ebx,eax  
004019C5  call         _Random32@0 (4019A6h)  ;<---- This function doesn't touch ebx
004019CA  mov          edx,0  
004019CF  div          eax,ebx     ;<---- That's where the error occurs
004019D1  mov          eax,edx  
004019D3  pop          edx  
004019D4  pop          ebx  
004019D5  ret

您知道可能导致此错误的原因吗?

我很想创建自己的随机数生成器。

RandomRange方法的背景:这很简单。你使用Randomize设置种子,将10移动到eax中将RandomRange保持在0-9之间。这就是我能为该函数找到的所有文档,所以我认为这就是它的全部内容。

3 个答案:

答案 0 :(得分:1)

我意识到这是一个古老的问题,但是我的一个朋友刚引用它。

您的mov eax, 10属于call RandomRange,因此您的代码示例应为:

randomCompNum PROC
    call Randomize               ;Sets seed

    mov  eax,10                  ;Keeps the range 0 - 9
    call RandomRange
    mov  compNum1,eax            ;First random number

L1: mov  eax,10                  ;Keeps the range 0 - 9
    call RandomRange
    .IF eax == compNum1          ;Checks if the second number is the same as the first
        jmp L1                   ;If it is, repeat call
    .ENDIF
     mov compNum2,eax            ;Second random number

L2: mov  eax,10                  ;Keeps the range 0 - 9
    call RandomRange
    .IF eax == compNum1          ;Checks if the third number is the same as the first
        jmp L2                   ;If it is, repeat
    .ELSEIF eax == compNum1      ;Checks if the third number is the same as the second
        jmp L2                   ;If it is, repeat
    .ENDIF
    mov compNum3,eax             ;Third random number stored

    ret
randomCompNum ENDP

mov eax,10是发送到RandomRange函数的参数,它在C中为RandomRange(10);。 请注意,因为RandomRange在eax中返回其结果,所以需要在每次调用之前进行设置。

答案 1 :(得分:0)

Random32  PROC
;
; Generates an unsigned pseudo-random 32-bit integer
;   in the range 0 - FFFFFFFFh.

Random32 CAN返回0,这可能就是为什么当你除以0时它会轰炸你:-)

Irvine源可用,只需修改RandomRange以便在从Random32返回时处理0

答案 2 :(得分:0)