如何生成大量随机数Ç [英] How to generate large random numbers C

查看:239
本文介绍了如何生成大量随机数Ç的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种方式来2在C ^ 64的顺序生成大量随机数...(亿 - 999999999),在一个公共密钥加密算法的使用(p和q)

我不想产生大于2 ^ 64小的数(即,小于100000000)。

有什么可以帮助我做到这一点?


解决方案

随机()返回一个长,这64位系统上应该是64位。如果你是一个32位系统上,你可以做到以下几点:

 的#include< inttypes.h>uint64_t中NUM;/ *添加code种子随机数发生器* /NUM = RAND();
NUM =(NUM<< 32)| RAND();//强制亿到999999999之间的界限值
NUM =(NUM%(999999999 - 100000000))+亿;

另外一个NIX系统上你可以读出的/ dev /随机到您的缓冲区:

 的#include< SYS / types.h中>
#包括LT&; SYS / stat.h>
#包括LT&;&fcntl.h GT;
#包括LT&;&inttypes.h GT;INT的fd;
uint64_t中NUM;
如果((FD =打开(/开发/随机,O_RDONLY)== -1)
{
    / *处理错误* /
};
阅读(FD,试验#,8);
关闭(FD);//强制亿到999999999之间的界限值
NUM =(NUM%(999999999 - 100000000))+亿;

A

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?

解决方案

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

这篇关于如何生成大量随机数Ç的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆