javarandombitsecure-random

How to generate a SecureRandom number with a specific bit range


I have maximum number of bits that is not bit aligned E.g. 35 and required to generate unique random number from 1 - 68719476734 (max number for 35 bits). Could use SecureRandom but will have to extract 5 bytes out of it and convert to Long maybe, but chances of collision seem to a concern. What are some options to generate a random for this range. Could i seed this random with nanoTime maybe if there is a collision and regenerate in this range.


Solution

  • First, a few comments:

    To generate a 35-bit random number, excluding value zero, just generate a long random value, take the last 35 bits, and redo if the value is zero.

    SecureRandom r = new SecureRandom();
    
    long value;
    do {
        value = r.nextLong() & ((1L << 35) - 1);
    } while (value == 0);