diff options
| author | Tatsuhiro Tsujikawa <tatsuhiro.t@gmail.com> | 2013-09-26 00:41:33 +0900 |
|---|---|---|
| committer | Tatsuhiro Tsujikawa <tatsuhiro.t@gmail.com> | 2013-09-26 00:41:33 +0900 |
| commit | 7f18494a8c1b714368e64e7abd7abb30c123a862 (patch) | |
| tree | 0df69e86d35051face0572012c98af5e696b85b0 /src/SimpleRandomizer.cc | |
| parent | ac996737e567c1ff29afbfb00acf22a2b4d57b7b (diff) | |
SimpleRandmizer: Fix certain bits generated by getRandomBytes are always 0
This is because in Linux RAND_MAX is 2**31-1 and we used int32_t to
hold random number from random() and got each bytes. This means that
highest bit is always unset. In little endian system, every 4n-th (n
>=0) byte has highest bit is unset. To fix this, we just use lower 2
bytes of random().
Diffstat (limited to 'src/SimpleRandomizer.cc')
| -rw-r--r-- | src/SimpleRandomizer.cc | 9 |
1 files changed, 5 insertions, 4 deletions
diff --git a/src/SimpleRandomizer.cc b/src/SimpleRandomizer.cc index fea7262f..9754d6cb 100644 --- a/src/SimpleRandomizer.cc +++ b/src/SimpleRandomizer.cc @@ -123,11 +123,12 @@ void SimpleRandomizer::getRandomBytes(unsigned char *buf, size_t len) } #else while (len) { + // If RAND_MAX is less than 2**16-1, we are in trouble. union { - int32_t r; - uint8_t b[4]; - } r = { (int32_t)random() }; - for (auto i = 0; i < 4 && len; ++i, --len) { + uint16_t r; + uint8_t b[2]; + } r = { (uint16_t)(random() & 0xffffu) }; + for (auto i = 0; i < 2 && len; ++i, --len) { *buf++ = r.b[i]; } } |
