Snippet:Pseudorandom numbers

From veswiki
Jump to: navigation, search

Sometimes you want to add a random number to your programming but you will have to make your own code to produce it.
A common way to make a pseudo-random number generator (PRNG) is do use a Linear Feedback Shift Register (LFSR).
This will give you a series of numbers from 0 to 255 in a seemingly randomized order.

You will however get the same series of values in the same order every time, your "seed" number will choose the start position.

Here's an example of a subroutine with 8-bit LFSR:

; In this example the pseudo random number is stored in register 1
; Also uses register 0 for temporary storage

LFSR:             ; Linear Feedback Shift Register
	as	1
	bz	doEor
	lr	0, A		; Save original number in r0
	sl	1		; shift one step left
	lr	1, A
	bz	noEor

	; Do XOR if b7 was 1, workaround for missing carry on "sl" 
	lr	A, 0
	ni	%10000000
	bz	noEor

	lr	A, 1
	xi	$2b     ; Do the XOR thing
	lr	1, A

The value used with XOR-function is $2B here, one of these other values can be used to give a different 256 byte non-repeating chain of values.
$1d, $2b, $2d, $4d, $5f, $63, $65, $69, $71, $87, $8d, $a9, $c3, $cf, $e7, $f5

When using $2B as XOR value the data will be this:
LFSR $2B.png

When using $71 as XOR value the data will be this:
LFSR $71.png

CodeBase64 used for reference