I want to generate a random 32-bit number. I am using rdrand for this. However, I am having some problems. Since the number can be no more than 32 bits large, I am doing rdrand eax. Here is where the problem arises:
I need to be able to refer to this 32-bit number in a 64-bit register since the rest of my codebase uses 64-bit registers. I figured that I could clear
raxwith axorto itself, and then only load half of it withrdrand eax. Then I could look atrax, have one half be at most a 32-bit number, and the other half be cleared.When I compare
raxwith the maximum 32-bit number size, 2147483647, I get very inconsistent results. Half of the time, the exit code is 1, meaning that the number inraxis, in fact, smaller than 32-bits. But the other half of the time I get 0. It's almost like the result ineaxis not always less than or equal to 2147483647, which is unexpected given what this documentation says.
Does anyone know what is going wrong in my thought process? I am very curious to know. (Note: I'm assembling with Clang on macOS.)
.global _main
.text
# how to generate a 32-bit random number that is in rax?
_main:
xor rax, rax # clear the top half of the eax-rax register pair
rdrand eax # a 32-bit number in rax
cmp rax, 2147483647
jle smaller_than_32 # rax <= MAX_32_BIT
xor rdi, rdi
jmp end
smaller_than_32:
mov rdi, 1
end:
mov rax, 0x2000001
syscall