Working on a code golf challenge which requires using the RDRAND hardware random number generator.
Examples
Set r12 to a random number [0,255]
rdrand ax
movzx r12,al
Set r8 to a random number [0,1]
rdrand r8
and r8,1
Question
I'm assuming the above examples are non-biased?
But, suppose the challenge required generating a random number in the range [0,N], say N=512, are there any biases introduced? If so, what's the correct assembly code to generate a non-biased random number from [0,N]?
Update
Based upon the comment
For power-of-2 ranges, just mask out the bits you want.
Perhaps this example will work by looking at a 2^10 range then masking the bits?
; Generate a random number until it is in the range [0, 512]
mov dword[num], 0
retry0:
rdrand eax
jnc retry0
and eax, 1023 ; Limit the range to [0, 1023] to fit into 10 bits
cmp eax, 512 ; Check if the number is within [0, 512]. (Rejection Sampling)
ja retry0 ; If above 512, generate again
mov [num], eax
As suggested in the comments section, here's my attempt at converting Lemire's Method to Nasm. It outputs a random 32-bit number from [0,N].
Basically, took Peter's C godbolt example and ported it to a Nasm example
Let me know if there are any glaring mistakes. Thanks.