faksel
faksel

Reputation: 125

How to generate a random number 2^128

how to generate a random number 2^128 using standard data types?

How to work with such large numbers in java?

Upvotes: 0

Views: 492

Answers (2)

One Man Crew
One Man Crew

Reputation: 9578

The BigInteger Constructs a randomly generated BigInteger, uniformly distributed over the range 0 to (2numBits - 1), inclusive.

The uniformity of the distribution assumes that a fair source of random bits is provided in rnd. Note that this constructor always constructs a non-negative 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;
    }

}

Upvotes: 4

Robert
Robert

Reputation: 42774

The largest Java primitive data type long is too small (64bit), therefore we have to use 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

Upvotes: 1

Related Questions