]> git.sur5r.net Git - cc65/blob - libsrc/common/rand.s
This commit was generated by cvs2svn to compensate for changes in r2,
[cc65] / libsrc / common / rand.s
1 ;       
2 ; Randum number generator
3 ;
4 ; Written and donated by Sidney Cadot - sidney@ch.twi.tudelft.nl
5 ;
6 ; May be distributed with the cc65 runtime using the same license.
7 ;
8 ;
9 ; int rand (void);
10 ; void srand (unsigned seed);
11 ;
12 ;  Uses 4-byte state.
13 ;  Multiplier must be 1 (mod 4)
14 ;  Added value must be 1 (mod 2)
15 ;  This guarantees max. period (2**32)
16 ;  Bits 8-22 are returned (positive 2-byte int)
17 ;  where 0 is LSB, 31 is MSB.
18 ;  This is better as lower bits exhibit easily
19 ;  detectable patterns.
20 ;
21
22         .export         _rand, _srand
23
24 .bss
25
26 rand:   .res    4               ; Seed
27
28 .code
29
30 _rand:  clc
31         lda     rand+0          ; SEED *= $01010101
32         adc     rand+1
33         sta     rand+1
34         adc     rand+2
35         sta     rand+2
36         adc     rand+3
37         sta     rand+3
38         clc
39         lda     rand+0          ; SEED += $31415927
40         adc     #$27
41         sta     rand+0
42         lda     rand+1
43         adc     #$59
44         sta     rand+1
45         pha
46         lda     rand+2
47         adc     #$41
48         sta     rand+2
49         and     #$7f            ; Suppress sign bit (make it positive)
50         tax
51         lda     rand+3
52         adc     #$31
53         sta     rand+3
54         pla                     ; return bit 8-22 in (X,A)
55         rts
56
57 _srand: sta     rand+0          ; Store the seed
58         stx     rand+1
59         lda     #0
60         sta     rand+2          ; Set MSW to zero
61         sta     rand+3
62         rts
63