From 4f3290514fdc554a17d3ce84f29dc047be867495 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=89milie=20Feral?= Date: Thu, 1 Feb 2018 16:37:36 +0100 Subject: [PATCH] [ion] Simulator/Emscripten/Blackbox: correct random implementation --- ion/src/shared/random.cpp | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/ion/src/shared/random.cpp b/ion/src/shared/random.cpp index 990a31d94..4f32f8186 100644 --- a/ion/src/shared/random.cpp +++ b/ion/src/shared/random.cpp @@ -3,10 +3,9 @@ uint32_t Ion::random() { /* rand() returns a pseudo-random integral number in the range between 0 and - * RAND_MAX which is garantueed to be at least 32767.*/ - uint32_t result = 0; - for (int i = 0; i < 131077; i++) { - result += rand(); - } - return result; + * RAND_MAX. We assert that RAND_MAX is at least 8 bit, this way we can merge + * four rand() calls to create a single 32 bit value. Merging is done using + * XOR, whose output is as likely to be a 1 as a 0. */ + static_assert(RAND_MAX >= (1<<8), "RAND_MAX is too small"); + return (rand() << 24) ^ (rand() << 16) ^ (rand() << 8) ^ rand(); }