Question:
Having trouble with the modulus operator in mASM?
anonymous
2010-01-23 09:27:42 UTC
I am trying to implement a pseudo random number generator using modulus in masm. The only problem is I am having trouble with the syntax of assembly.

Here is the code that I wrote in C++:

#include
#include
using namespace std;

int random(int max)
{
int seed = timeGetTime();
return (seed % max);
}

int main()
{
cout << random(4);
return 0;
}

Now, I am having trouble implementing modulus in mASM

To my understanding, the following function should be the following in assembly:

.DATA?
seed DWORD ?

.CODE
start:
call timeGetTime
mov seed, eax
;to my understanding i have to call the MOD function. However, the following does not work:
MOD seed, 4
end start

So my question is, how can I preform the modulus operator in mASM so that I can generate a random number?
Four answers:
husoski
2010-01-23 10:34:04 UTC
Division produces both an integer quotient and remainder, so use DIV for unsigned remainder or IDIV (the usual remainder function implemented by C as the % operator). In either case, EDX and EAX have the 64-bit dividend (numerator) with the high 32 bits in EDX.



So, signed integer division with 32-bit arguments to produce ARGX/ARGY and ARGX%ARGY looks like:



MOV EAX,ARGX ; Get 32-bit signed dividend into EAX

CDQ ; sign extend into EDX

IDIV ARGY ; Now EAX = ARGX/ARGY and EDX = ARGX%ARGY



Unsigned 32-bit division/remainder looks like:



MOV EAX,ARGX ; Get 32-bit unsigned dividend into EAX

SUB EDX,EDX ; zero extend into EDX

IDIV ARGY ; Now EAX = ARGX/ARGY and EDX = ARGX%ARGY
Ratchetr
2010-01-23 10:06:04 UTC
You could always look at the C++ generated code in the debugger and see what it does:



return (seed % max);

00C81680 mov eax,dword ptr [seed]

00C81683 cdq

00C81684 idiv eax,dword ptr [max]

00C81687 mov eax,edx
Paul
2010-01-23 09:38:05 UTC
MOD is not an opcode - it's a MASM operator for assembly-time expressions - you need to understand the difference.



Just use C's % operator - it's going to be a lot easier.
?
2016-12-18 18:41:33 UTC
the only one I ever had replaced into the only my brother in regulation gave me while he further over a working laptop or laptop approximately 15 years in the past. i did not even look into it, I in basic terms watched him and discovered all i mandatory to nicely known. What do you want help with pockey?


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...