I am trying to create an array of random numbers in ARMv8.
I am successful in creating an array of random numbers, however, my instruction which constrains the array; specifically the and
instruction and the cmp are constraining it to a range of 0 to 12 instead of 0 to 9.
here's my code:
bl rand //branch to random num
and x22, x0, 0x0C
add x18,x18, x22
cmp x22,x23 //compare x23 register to x22
b.lt mini //branch to minimum calculation
as you can see I'm using and x0 with 0x0C which is 12 in hex.
Some say the best would be do and with 0xFF or 255 in hex but this is giving me very large numbers and thus Ox0C is giving me the best results so far but not ideal as I need them to be between 0 and 9.
an example table I'm currently getting when running the program:
0 0 0 8 0
12 8 12 4 12
4 4 0 4 12
4 12 12 12 4
12 8 8 8 4
and the ideal table example (I just removed 1 or 2 from 12 to demonstrate single digit random table, this is not an actual generation):
0 0 0 8 0
2 8 1 4 2
4 4 0 4 1
4 1 1 2 4
1 8 8 8 4
It can't be done using only and
. The bit patterns for 1, 2, 4, and 8 are
0b0001
0b0010
0b0100
0b1000
The only bitmask that permits all of them is 0b1111, which permits any number up to 15. If you want to constrain your values to the range 0-9, you've got two basic options:
and
with a bitmask of 0x0f
to reduce the range to 0-15. If the number is larger than 9, you discard it and generate a new random number. This is unbiased, but has no guarante of how long it will take to generate an acceptable number.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.