News:

11 March 2016 - Forum Rules

Main Menu
Menu

Show posts

This section allows you to view all posts made by this member. Note that you can only see posts made in areas you currently have access to.

Show posts Menu

Messages - tertu

#1
Programming / Re: Random number generator in 6502 assembly
September 30, 2020, 01:05:24 PM
Here's something that I found that doesn't need division. It's pretty much what Bregalad was suggesting.


random_in_range:
  sta scratch
  clc
  sbc #1
  ora #1
  ldx #$FF
  ;determine which mask to use by counting leading zeroes
  @count: inx
  rol a
  bcc @count
  ;loop until random <= range-1
  @try: jsr random
  and mask_bytes, x
  cmp scratch
  bcs @try
  rts
mask_bytes: .db $FF, $7F, $3F, $1F, $0F, $07, $03, $01


EDIT: As other people have said, if the period's too short this can cause problems, but there are algorithms you can use that fit pretty nicely on the 6502 and have periods on the order of 232, which is probably long enough that it's fine.