From: Dam Sunwoo Date: Tue, 10 Jan 2012 00:08:20 +0000 (-0600) Subject: Base: Fixed shift amount in genrand() to work with large numbers X-Git-Tag: stable_2012_06_28~275^2~39 X-Git-Url: https://git.libre-soc.org/?a=commitdiff_plain;h=3f9e352de4e1ac34e1f0b83c3f66af2175b524f4;p=gem5.git Base: Fixed shift amount in genrand() to work with large numbers The previous version didn't work correctly with max integer values (2^31-1 for 32-bit, 2^63-1 for 64bit version), causing "shift" to become -1. For smaller numbers, it wouldn't have caused functional errors, but would have resulted in more than necessary loops in the while loop. Special-cased cases when (max + 1 == 0) to prevent the ceilLog2 functions from failing. --- diff --git a/src/base/random.cc b/src/base/random.cc index 457b0c98b..cffeddec9 100644 --- a/src/base/random.cc +++ b/src/base/random.cc @@ -29,6 +29,7 @@ * Ali Saidi */ +#include #include "base/fenv.hh" #include "base/intmath.hh" #include "base/misc.hh" @@ -67,7 +68,10 @@ Random::genrand(uint32_t max) { if (max == 0) return 0; - int log = ceilLog2(max) + 1; + if (max == std::numeric_limits::max()) + return genrand(); + + int log = ceilLog2(max + 1); int shift = (sizeof(uint32_t) * 8 - log); uint32_t random; @@ -83,7 +87,10 @@ Random::genrand(uint64_t max) { if (max == 0) return 0; - int log = ceilLog2(max) + 1; + if (max == std::numeric_limits::max()) + return genrand(); + + int log = ceilLog2(max + 1); int shift = (sizeof(uint64_t) * 8 - log); uint64_t random;