我目前正在编写一个生成伪随机int的随机数生成器,然后返回一个表示int值中最低有效位的int。
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;
}
}
该程序的目的是能够创建一个返回值,然后测试类可以写入文件,并且因为输出是随机生成的数字的最低有效位,所以输出将是加密安全的。< / p>
然而,当试图提出测试类的实现时,我很难弄清楚如何处理输出。我需要测试类能够做的是将512位写入输出文件。但是,FileOuputStream类只能将字节写入输出文件。
我想要做的是弄清楚是否有方法将我的随机数生成器中的单个1或0输出分组为字节值,但到目前为止我还没有找到任何东西这是Java支持的。
答案 0 :(得分:5)
您可以使用<<
运算符(或位移和赋值运算符<<=
)使用位移来构造字节(或整数或长整数)
byte b = 0;
for (int i = 0; i < 8; i++) {
b <<= 1;
b |= rng.next();
}