NES Advantage

Making NES Development Less Hard

Random Number Generation 2: 16-Bit LFSR

This algorithm results in two 8-bit numbers that form a single 16-bit value: a low byte in A, and a high byte in Y. As you'll see in the code, the high byte actually gets scrambled less, so if you only need a random 8-bit number, use the low byte.

Here's the driver code, which itself calls two subroutines, given immediately following. I won't step through it all, having done so already for the smaller LFSR above. Truth be told, I can't explain exactly how this algorithm operates. I'm taking it on faith that it does what it should: cycle through 65,535 different values in an unpredictable order based on a starting seed value. But it's what I use in my games!

.proc lfsr JSR rand64k JSR rand32k LDA seed0+1 EOR seed1+1 TAY LDA seed0 EOR seed1 RTS .endproc .proc rand64k LDA seed0+1 ASL ASL EOR seed0+1 ASL EOR seed0+1 ASL ASL EOR seed0+1 ASL ROL seed0 ROL seed0+1 RTS .endproc .proc rand32k LDA seed1+1 ASL EOR seed1+1 ASL ASL ROR seed1 ROL seed1+1 RTS .endproc
Copyright ©2024 Nathaniel Webb/Nat20 Games