]> git.sur5r.net Git - cc65/blobdiff - libsrc/common/rand.s
Fix broken rand() implementation. The high 8 bits were unused, reducing it to a 24...
[cc65] / libsrc / common / rand.s
index 51959619b3d6fa5420de94ab158c7a09c610810b..8ad7bcdb48bd575539948fdc6852b3dfdd992f46 100644 (file)
@@ -1,4 +1,4 @@
-;      
+;
 ; Randum number generator
 ;
 ; Written and donated by Sidney Cadot - sidney@ch.twi.tudelft.nl
 ;  detectable patterns.
 ;
 
-       .export         _rand, _srand
+        .export         _rand, _srand
 
-.bss
+.data
 
-rand:          .res    4               ; Seed
+; The seed. When srand() is not called, the C standard says that that rand()
+; should behave as if srand() was called with an argument of 1 before.
+rand:   .dword   1
 
 .code
 
-_rand: clc
-       lda     rand+0          ; SEED *= $01010101
-       adc     rand+1
-       sta     rand+1
-       adc     rand+2
-       sta     rand+2
-       adc     rand+3
-       sta     rand+3
-       clc
-       lda     rand+0          ; SEED += $31415927
-       adc     #$27
-       sta     rand+0
-       lda     rand+1
-       adc     #$59
-       sta     rand+1
-       pha
-       lda     rand+2
-       adc     #$41
-       sta     rand+2
-       and     #$7f            ; Suppress sign bit (make it positive)
-       tax
-       lda     rand+3
-       adc     #$31
-       sta     rand+3
-       pla                     ; return bit 8-22 in (X,A)
-       rts
-
-_srand:        sta     rand+0          ; Store the seed
-       stx     rand+1
-       lda     #0
-       sta     rand+2          ; Set MSW to zero
-       sta     rand+3
-       rts
+_rand:  clc
+        lda     rand+0          ; SEED *= $01010101
+        adc     rand+1
+        sta     rand+1
+        adc     rand+2
+        sta     rand+2
+        adc     rand+3
+        sta     rand+3
+        clc
+        lda     rand+0          ; SEED += $31415927
+        adc     #$27
+        sta     rand+0
+        lda     rand+1
+        adc     #$59
+        sta     rand+1
+        lda     rand+2
+        adc     #$41
+        sta     rand+2
+        and     #$7f            ; Suppress sign bit (make it positive)
+        tax
+        lda     rand+3
+        adc     #$31
+        sta     rand+3
+        rts                     ; return bit (16-22,24-31) in (X,A)
+
+_srand: sta     rand+0          ; Store the seed
+        stx     rand+1
+        lda     #0
+        sta     rand+2          ; Set MSW to zero
+        sta     rand+3
+        rts
+