Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Random number generation in assembly NASM

I am working on a university project in assembly nasm. The only problem is i am not able to generate an even random number between 162 and 278. I have tried many algorithms but cant seem to restrict the number in range.

Is there a small trick or tweak to get the desired number in range? The aim is to display a fruit randomly on the screen(It is mainly a snake game).

like image 851
Muhammad Hamza Avatar asked Oct 21 '25 02:10

Muhammad Hamza


2 Answers

generate an even random number between 162 and 278

Step 1

"generate random number"
The task of displaying a fruit in a snake game is not too demanding, so I think using the TimeStampCounter is quite ok. You'll continu with the low dword found in EAX.

-

rdtsc                        ; -> EDX:EAX

Step 2

"number between 162 and 278"
To restrict the number to your desired range of [162,278], you calculate
(RandomNumber mod NumbersInTheRange) + StartOfTheRange.

  • RandomNumber is the EAX register from the 1st step.
  • NumbersInTheRange is upper bound - lower bound + 1. Don't forget that +1.
  • StartOfTheRange is its lower bound.

-

xor     edx, edx             ; Required because there's no division of EAX solely
mov     ecx, 278 - 162 + 1   ; 117 possible values
div     ecx                  ; EDX:EAX / ECX --> EAX quotient, EDX remainder
mov     eax, edx             ; -> EAX = [0,116]
add     eax, 162             ; -> EAX = [162,278]

Step 3

"even number"
Make the number even by dropping its lowest bit.

-

and     eax, -2              ; -> EAX = {162,164,...,276,278}
like image 164
Sep Roland Avatar answered Oct 23 '25 02:10

Sep Roland


I look a little bit in this post: nasm random number generator function. Maybe you can try (rdtsc % (278 - 162) / 2 + 162 / 2) * 2. I hope I helped you :)

like image 32
Pocol Florin Avatar answered Oct 23 '25 01:10

Pocol Florin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!