1
我目前正在编写一个随机数生成器,它生成一个伪随机int,然后返回一个int值,表示int值中的最低有效位。从java中的各个位构造一个字节
public class RNG {
//algorithm input: first input is the seed
private int x;
//primes for calculating next random number
private int p;
private int q;
//constructor
public RNG()
{
p = getPrime();
q = getPrime();
//make sure p and q are not equal
while(p == q)
{
q = getPrime();
}
//seed must not be divisible by p or q
//easiest way is to make the seed another prime number
//this prime does not need to be congruent to 3 mod 4, so
//getPrime() is not used.
x = (BigInteger.probablePrime(8, new Random())).intValue();
}
//return a pseudorandom prime number using java.util.Random such that
//the number is congruent to 3 mod 4
private int getPrime()
{
Random rand = new Random();
int i;
while(true)
{
//generates a random BigInteger. The probability
//this BigInteger is composite is less than 2^-100
//bitLength is 8 so maximum prime value is 251
i = (BigInteger.probablePrime(8, rand)).intValue();
if((i % 4) == (3 % 4))
{
break;
}
}
return i;
}
public int next()
{
//calculate next algorithm input
int next = (x * x) % (p * q);
//set algorithm input for next next() call
x = next;
//return least significant bit
return next & 1;
}
}
的方案的目的是要能够建立一个返回值,该值的测试类可以再写入到文件中,并且由于输出是随机生成的数字的至少显著位输出将是密码安全。
但是,当试图想出测试类的实现时,我无法弄清楚如何处理输出。我需要测试类能够做的是将512位写入输出文件。但是,FileOuputStream类只能将字节写入输出文件。
我想要做的是找出是否有办法将来自随机数生成器的单个1或0个输出分组为字节值,但到目前为止我还没有发现任何Java支持的东西。
移做你知道](http://docs.oracle.com/javase/8/docs/api/java/util/BitSet.html)? – Radiodef
@Norsk顺便说一句...那里的答案创建了一个物理文件。另一个答案是你不能创建一个虚拟文件。 – Radiodef