Search code examples
randomintegermasm32

masm32 random integer 0-9


I'm learning masm32 and I need the program to generate a random integer from range 0-9 to compare to the user input. I have no problems with the comparing if I do have an integer. Is there an easy way to generate a new random integer from said range every time the program is run?

I know there's the Irvine32 library, but is there a way to do it without having to download extra libraries?

Thanks.

Also, this:

invoke GetTickCount
invoke nseed, eax
invoke nrandom, 10
mov number, eax

push offset number
call StdOut

Gives me some smiley faces not numbers, is there a way to make it work?


Solution

  • Since you are using MASM32, it includes documentation for all of its functions in the library, so RTFM!!! Open up \masm32\help and take a look at the help files!

    In order to display a number to the screen, you need to first convert the number to its ASCII equivalent. ASCII "2" is not the same as 2. You can role your own or use the DWORD to ASCII function in the MASM32 library called dwtoa.

    So using that function your code would become:

    invoke  GetTickCount
    invoke  nseed, eax
    invoke  nrandom, 10
    invoke  dwtoa, eax, offset lpszNumber
    invoke  StdOut, offset lpszNumber
    

    Where lpszNumber is defined in the .data? section as: lpszNumber db 2 dup (?) of course, make the buffer big enough to hold the number and NULL terminator. With that code, each time you start your program, it will generate a random number between 0 and 9, convert to ASCII and print to console.

    On top of including documentation for the functions included in MASM32, it includes the source for all the functions. Open \masm32\m32lib and you can take a look at the code to see how everything is done... you can even modify for your own use.