]> git.sur5r.net Git - cc65/blob - libsrc/common/rand.s
forgot to update comments from earlier #323 rand.s change
[cc65] / libsrc / common / rand.s
1 ;
2 ; Randum number generator
3 ;
4 ; Written and donated by Sidney Cadot - sidney@ch.twi.tudelft.nl
5 ; 2016-11-07, modified by Brad Smith
6 ;
7 ; May be distributed with the cc65 runtime using the same license.
8 ;
9 ;
10 ; int rand (void);
11 ; void srand (unsigned seed);
12 ;
13 ;  Uses 4-byte state.
14 ;  Multiplier must be 1 (mod 4)
15 ;  Added value must be 1 (mod 2)
16 ;  This guarantees max. period (2**32)
17 ;  The lowest bits have poor entropy and
18 ;  exhibit easily detectabl patterns, so
19 ;  only the upper bits 16-22 and 24-31 of the
20 ;  4-byte state are returned.
21 ;
22 ;  The best 8 bits, 24-31 are returned in the
23 ;  low byte A to provide the best entropy in the
24 ;  most commonly used part of the return value.
25 ;
26
27         .export         _rand, _srand
28
29 .data
30
31 ; The seed. When srand() is not called, the C standard says that that rand()
32 ; should behave as if srand() was called with an argument of 1 before.
33 rand:   .dword   1
34
35 .code
36
37 _rand:  clc
38         lda     rand+0          ; SEED *= $01010101
39         adc     rand+1
40         sta     rand+1
41         adc     rand+2
42         sta     rand+2
43         adc     rand+3
44         sta     rand+3
45         clc
46         lda     rand+0          ; SEED += $31415927
47         adc     #$27
48         sta     rand+0
49         lda     rand+1
50         adc     #$59
51         sta     rand+1
52         lda     rand+2
53         adc     #$41
54         sta     rand+2
55         and     #$7f            ; Suppress sign bit (make it positive)
56         tax
57         lda     rand+3
58         adc     #$31
59         sta     rand+3
60         rts                     ; return bit (16-22,24-31) in (X,A)
61
62 _srand: sta     rand+0          ; Store the seed
63         stx     rand+1
64         lda     #0
65         sta     rand+2          ; Set MSW to zero
66         sta     rand+3
67         rts
68
69