]> git.sur5r.net Git - cc65/blob - libsrc/common/rand.s
Removed (pretty inconsistently used) tab chars from source code base.
[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 .data
25
26 ; The seed. When srand() is not called, the C standard says that that rand()
27 ; should behave as if srand() was called with an argument of 1 before.
28 rand:   .dword   1
29
30 .code
31
32 _rand:  clc
33         lda     rand+0          ; SEED *= $01010101
34         adc     rand+1
35         sta     rand+1
36         adc     rand+2
37         sta     rand+2
38         adc     rand+3
39         sta     rand+3
40         clc
41         lda     rand+0          ; SEED += $31415927
42         adc     #$27
43         sta     rand+0
44         lda     rand+1
45         adc     #$59
46         sta     rand+1
47         pha
48         lda     rand+2
49         adc     #$41
50         sta     rand+2
51         and     #$7f            ; Suppress sign bit (make it positive)
52         tax
53         lda     rand+3
54         adc     #$31
55         sta     rand+3
56         pla                     ; return bit 8-22 in (X,A)
57         rts
58
59 _srand: sta     rand+0          ; Store the seed
60         stx     rand+1
61         lda     #0
62         sta     rand+2          ; Set MSW to zero
63         sta     rand+3
64         rts
65
66