我正在寻找一种在 C 中生成大约 2^64 的大随机数的方法...(100000000 - 999999999),用于公钥加密算法(如 p 和 q)。
我不想生成小于 2^64(即小于 100000000)的数字。
有什么可以帮助我做到这一点吗?
最佳答案
random() 返回一个 long,在 64 位系统上应该是 64 位。如果您使用的是 32 位系统,您可以执行以下操作:
#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;
或者在 NIX 系统上,您可以将/dev/random 读入您的缓冲区:
#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;
一个
关于c - 如何生成大的随机数 C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7920860/