簡體   English   中英

如何生成一個隨機數2 ^ 128

[英]How to generate a random number 2^128

如何使用標准數據類型生成2 ^ 128的隨機數?

如何在Java中處理這么大的數字?

BigInteger構造一個隨機生成的BigInteger,均勻分布在0到(2numBits-1)(包括0和2)之間。

分布的均勻性假定在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;
    }

}

最大的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 number

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM