如何使用标准数据类型生成随机数2^128?
如何在java中使用这么大的数字
发布于 2019-03-24 13:50:57
BigInteger构造一个随机生成的BigInteger,在0到(2 2numBits 1)的范围内均匀分布,包括在内。
分布的均匀性假设在rnd中提供了一个公平的随机比特源。注意,这个构造函数总是构造一个非负的BigInteger。
import java.math.BigInteger;
import java.util.Random;
public class BigRandom {
public static void main(String[] args) {
BigInteger result = getRandomBigInteger();
System.out.println(result);
}
public static BigInteger getRandomBigInteger() {
Random rand = new Random();
BigInteger result = new BigInteger(128, rand); // (2^128-1) maximum value
return result;
}
}发布于 2019-03-24 13:41:56
最大的Java原语数据类型long太小(64位),因此我们必须使用BigInteger:
SecureRandom rnd = new SecureRandom();
byte[] data = new byte[16]; // 16 * 8 = 128 bit
rnd.nextBytes(data);
BigInteger bigInt = new BigInteger(1, data); // interpret the data as positive numberhttps://stackoverflow.com/questions/55324338
复制相似问题