Skip to contentSkip to conversation

Created RAND_32 and RAND_64 macros.

PATCH New [email protected] 1 participant 1 message Mar 6, 2015

lore
Share & tools
lore
#0 lore raw

PATCH 2/12 Created RAND_32 and RAND_64 macros.

From: Tyson Smith <[email protected]>

These macros will generate a random number between 0 and 2^32 - 1 or 2^64 - 1 respectively. There is also a compile time check to verify that a full 2^n bits of randomness will be generated (depends on RAND_MAX).

---
 include/random.h | 8 ++++++++
 random.c         | 4 ++--
 2 files changed, 10 insertions(+), 2 deletions(-)
include/random.h +8 -0
index dbff344..f070568 100644
@@ -1,10 +1,18 @@
 #pragma once
 
+#include <stdlib.h>
 #include "child.h"
 #include "types.h"
 
 #define ONE_IN(x)				((rand() % x) == 0)	// limit of RAND_MAX-1
 
+#if RAND_MAX == 0x7FFFFFFF
+#define RAND_32()				((rand() << 1) | (rand() & 1))
+#define RAND_64()				(((0ULL | rand()) << 33) | ((0ULL | rand()) << 2) | (rand() & 0x3))
+#else
+#error "Unexpected RAND_MAX value. Please add support."
+#endif
+
 extern unsigned int seed;
 unsigned int init_seed(unsigned int seed);
 void set_seed(struct childdata *child);
random.c +2 -2
index 6a2e90e..f425ed5 100644
@@ -132,7 +132,7 @@ static unsigned int __rand32(void)
 		break;
 	case 1:	r = randbits(32);
 		break;
-	case 2: r = rand();
+	case 2: r = RAND_32();
 		break;
 	case 3:	r = rand8x8();
 		break;
@@ -216,7 +216,7 @@ u64 rand64(void)
 			break;
 		case 1:	r = randbits(64);
 			break;
-		case 2:	r = rand32() | rand32() << 31;
+		case 2:	r = RAND_64();
 			break;
 		case 3:	r = rand8x8();
 			break;
Signature · 1 line
1.9.1