0

Im trying to generate random number by these:

uint32_t rnd;
uint32_t max = 65536;
__asm {
    mov eax, 0
    rdrand ax
    mov rnd, eax
    fldz
    fiadd dword ptr rnd
    fidiv dword ptr max
}

Problem is, visiual studio is saying that rdrand is illegal. How can i solve this ? Im using x86 intel pentium instruction codes. Thanks

  • 1
    I don't know how VS works when dealing with assembly but the recent versions should recognize `rdrand`. Unless by "using x86 intel Pentium instruction codes" you mean that you are using a specific assembly directive to limit the assembler to the Pentium instruction set (e.g. like the `.586` in TASM/MASM). In that case, you need to drop that directive or use another source of random. Or you can emit the opcode directly (`66 0f c7 f0`) but it's a bit ugly. – Margaret Bloom May 13 '21 at 12:43
  • 3
    Also, technically speaking, you should check if `rdrand` returned a valid number. Judging from your previous question it is probably better to use a pseudo-RNG (like [xorshift](https://en.wikipedia.org/wiki/Xorshift)) seeded with `rdtsc`. But your professor may want you to use the code given. – Margaret Bloom May 13 '21 at 12:45
  • 1
    Which visual studio? Some of them predate `rdrand` – harold May 13 '21 at 13:39
  • Do you mean your CPU doesn't support it, so it builds ok but faults at run-time? It was new in IvyBridge for Intel, and AMD maybe not until Zen. https://en.wikipedia.org/wiki/RDRAND. In that case you'll definitely have to avoid `rdrand`. You could perhaps use `rdtsc` / `movzx eax, ax` to get randomness *once*, but for repeated runs it wouldn't be uniform necessarily. – Peter Cordes May 13 '21 at 17:45
  • Of course, if you're only generating numbers in such a tiny range (16-bit) and using each one completely independently (so it doesn't matter what *order* you get them in), you could just loop over all 16-bit numbers with `rnd++`. That will give you a uniform distribution - all values appear exactly once. Or if you need a random X and Y, then loop a 32-bit counter and break it into two 16-bit halves to get all possible combinations of X and Y, fully covering every point in the plane that you can represent with your low-precision RNG that can only produce 2^16 different doubles. – Peter Cordes May 13 '21 at 17:51
  • [How to generate random float number in C](https://stackoverflow.com/q/13408990) is the simple way, not necessarily great. Use any PRNG implementation you want, if you don't just call C `rand()`. Also [Random float number generation](https://stackoverflow.com/q/686353). Obviously anything you can do in C, you can do in asm. – Peter Cordes May 13 '21 at 19:25

0 Answers0