-1

I am attempting to generate a random 20 digit BigInteger in Java.

So far, I have been able to generate a fixed length hex value.

    // generate a user-specified number of random bytes
    public void getRandomNumber(int count) {

        byte[] bytes = new byte[count];
        new SecureRandom().nextBytes(bytes);
        String random = new String(Hex.encode(bytes));
        System.out.println(random);
    }

This is ideal for a fixed length hex generation. But I struggle to find an efficient method of doing this for a decimal representation; when converting from hex to BigInteger(hexValue, 16), the length will vary.

I have considered trying this by setting upper and lower bounds, or by generating something big enough and trimming to the desired length, but those methods do not feel very clean.

Edit: The solution I have came up with that is working fine in my program:

// generate a random number with specified bit length
    public void getTokenID() {
        int count = 64;
        SecureRandom rnd = new SecureRandom();
        BigInteger randomCountLength;
        String token;

        do {
            randomCountLength = new BigInteger(count, rnd);
            token = randomCountLength.toString();
        } while (token.length() != 20);

        Tid = token;
    }
lb-99
  • 33
  • 5
  • When you say 20 digit, do you mean decimal, hex or binary digits? – Artjom B. Feb 17 '21 at 19:15
  • @ArtjomB. Sorry, I meant decimal digits. I think I have found the solution to my problem - although maybe it is not the most efficient solution I will add it to my post. – lb-99 Feb 17 '21 at 19:24
  • @lb-99 it's better to post a [self-answer](https://stackoverflow.com/help/self-answer) than edit your answer into the post. This keeps things clear and separate and lets people vote on the answer along with all the others--it may not be the best solution. Thanks. – ggorlen Feb 18 '21 at 04:32
  • @ggorlen for some reason I do not get the option to answer this question - potentially as it has been marked as duplicate? – lb-99 Feb 18 '21 at 11:44

1 Answers1

1

What I understand that your problem is to generate random number with fixed length (fixed number of digits)

It is obvious that using hex value will work since any hex digit represent 4 bytes. So when you fix the length of bytes (bytes table in your code) it work fine

What I advice you when dealing with decimal number is :

1- There is methods for generating random number with lower and upper bound, for example Random betwen 5 and 10, so if you want for example a random number with 20 digits , you have to generate random number between (10^19) and (10^20-1)

2- The second is hardcoded method to make a loop of 20 iterations when you generate random digit (between 0 and 9 exept the the digit of strong weight which must be between 1 and 9) and you get the number.

NASSIM ADRAO
  • 145
  • 1
  • 9