]> git.sur5r.net Git - cc65/blob - libsrc/common/rand.s
Fix broken rand() implementation. The high 8 bits were unused, reducing it to a 24...
[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         lda     rand+2
48         adc     #$41
49         sta     rand+2
50         and     #$7f            ; Suppress sign bit (make it positive)
51         tax
52         lda     rand+3
53         adc     #$31
54         sta     rand+3
55         rts                     ; return bit (16-22,24-31) in (X,A)
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
64