## 0 Replies - 1562 Views - Last Post: 10 May 2009 - 01:21 AM

### #1 NickDMax Reputation: 2255
• Posts: 9,245
• Joined: 18-February 07

# Random Number Generator

Posted 10 May 2009 - 01:21 AM

Description: To use the function you would normally first seed the generator with some unpredictable value (such as the system clock value). Note that this is NOT a cryptographically secure generator! It is generally best only only actually use a few bits from an LCG.A Basic LCG example. The function uses the C calling convention (so it can integrate with C/C++).
```.386p
PUBLIC _RandomGen, _RandomGenSeed

; A basic Linear Congruential Generator capable of generating
; pseudorandom numbers -- As you can see, implemented in assembly
; using a modulus of a power of 2 (the machine word size), the
; program is very simple.

MODEL flat, C
_DATA	segment dword public use32 'DATA'
CurrentValue    dd  0   ; Since LCG's are iterative we need to be able to save the last value.
_DATA	ends

_TEXT    segment dword public use32 'CODE'

; Our equation is X(i+1) = A * X(i) + C mod 2^32
; These two constants used for A and C
AValue  EQU     41C64E6Dh    ;Value for A in ASCII C's rand() function
CValue  EQU     03039h

_RandomGen proc near                   ; extern "C" unsigned int RandomGen();
push    ebp
mov     ebp, esp                   ; set base pointer to stack pointer
push    ebx
mov     eax, CurrentValue      ;initialize with previous value
mov     ecx, AValue            ; We will be using the formula:
mov     ebx, CValue            ; ebx*eax + ebx and for mod we will just
;ignore the value in edx.
mul     ecx
mov     CurrentValue, eax
ROR     eax, 4                  ;Using rotate to mask hifrequency patterns.
pop     ebx
pop     ebp
ret
_RandomGen endp

_RandomGenSeed proc near
push    ebp
mov     ebp, esp
mov     eax, [ebp + 8]
mov     CurrentValue, eax
pop     ebp
ret
_RandomGenSeed endp

_TEXT ENDS

END

; Example useage:
;
;#include <stdio.h>
;
;extern int RandomGen(void);
;extern void RandomGenSeed(int);
;
;int main() {
;    int i;
;    unsigned int a;
;    RandomGenSeed(10);  //Seed the random number generator with some value
;    for(i = 0; i < 100; ++i) {
;        a = RandomGen();
;        printf("Random Value: %un", a);
;    }
;
;    return 0;
;}
```

Is This A Good Question/Topic? 0

Page 1 of 1

 .related ul { list-style-type: circle; font-size: 12px; font-weight: bold; } .related li { margin-bottom: 5px; background-position: left 7px !important; margin-left: -35px; } .related h2 { font-size: 18px; font-weight: bold; } .related a { color: blue; }