trinity.vger.kernel.org archive mirror
 help / color / mirror / Atom feed
* [PATCH 02/12] Created RAND_32 and RAND_64 macros.
@ 2015-03-06 22:29 tyson.w.smith
  0 siblings, 0 replies; only message in thread
From: tyson.w.smith @ 2015-03-06 22:29 UTC (permalink / raw)
  To: davej; +Cc: trinity, Tyson Smith

From: Tyson Smith <tysmith@motorola.com>

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(-)

diff --git a/include/random.h b/include/random.h
index dbff344..f070568 100644
--- a/include/random.h
+++ b/include/random.h
@@ -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);
diff --git a/random.c b/random.c
index 6a2e90e..f425ed5 100644
--- a/random.c
+++ b/random.c
@@ -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;
-- 
1.9.1

^ permalink raw reply related	[flat|nested] only message in thread

only message in thread, other threads:[~2015-03-06 22:29 UTC | newest]

Thread overview: (only message) (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
2015-03-06 22:29 [PATCH 02/12] Created RAND_32 and RAND_64 macros tyson.w.smith

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for NNTP newsgroup(s).