I'm looking for a way to generate large random numbers on the order of 2^64 in C... (100000000 - 999999999), to use in a public key encryption algorithm (as p and q).
I do not want to generate a number smaller than 2^64 (that is, smaller than 100000000).
Is there anything that could help me to do this?
The rand() and srand() functions are used to generate random numbers in C/C++ programming languages. The rand() function gives same results on every execution because the srand() value is fixed to 1.
In this program we call the srand () function with the system clock, to initiate the process of generating random numbers. And the rand () function is called with module 10 operator to generate the random numbers between 1 to 10. srand(time(0)); // Initialize random number generator.
int r = rand(); // Returns a pseudo-random integer between 0 and RAND_MAX.
rand() function is an inbuilt function in C++ STL, which is defined in header file <cstdlib>. rand() is used to generate a series of random numbers.
You could combine two 4-byte random integers to produce an 8-byte one:
#include <stdint.h>
...
uint64_t random =
(((uint64_t) rand() << 0) & 0x00000000FFFFFFFFull) |
(((uint64_t) rand() << 32) & 0xFFFFFFFF00000000ull);
Since rand
returns int
, and sizeof(int) >= 4
on almost any modern platform, this code should work. I've added the << 0
to make the intent more explicit.
The masking with 0x00000000FFFFFFFF
and 0xFFFFFFFF00000000
is to prevent overlapping of the bits in the two numbers in case sizeof(int) > 4
.
EDIT
Since @Banthar commented that RAND_MAX
is not necessarily 2 ^ 32
, and I think it is guaranteed to be at least 2 ^ 16
, you could combine four 2-byte numbers just to be sure:
uint64_t random =
(((uint64_t) rand() << 0) & 0x000000000000FFFFull) |
(((uint64_t) rand() << 16) & 0x00000000FFFF0000ull) |
(((uint64_t) rand() << 32) & 0x0000FFFF00000000ull) |
(((uint64_t) rand() << 48) & 0xFFFF000000000000ull);
random() returns a long which on a 64bit system should be 64 bits. If you are on a 32bit system you could do the following:
#include <inttypes.h>
uint64_t num;
/* add code to seed random number generator */
num = rand();
num = (num << 32) | rand();
// enforce limits of value between 100000000 and 999999999
num = (num % (999999999 - 100000000)) + 100000000;
Alternatively on a NIX system you could read /dev/random into your buffer:
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <inttypes.h>
int fd;
uint64_t num;
if ((fd = open("/dev/random", O_RDONLY) == -1)
{
/* handle error */
};
read(fd, &num, 8);
close(fd);
// enforce limits of value between 100000000 and 999999999
num = (num % (999999999 - 100000000)) + 100000000;
A
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With