Uniformly Random Integers in Java: A Negative Experience

In Java, there is a difference between these calls:


Random random = new SecureRandom();

int result = random.nextInt();

int resultBounded = random.nextInt(Integer.MAX_VALUE);

The first result will range from -Integer.MAX_VALUE+1 to Integer.MAX_VALUE.
The bounded result will range from 0 to Integer.MAX_VALUE (inclusive).

All of this is clearly defined in the Javadoc.

However, when combined with bitwise operators that preserve the sign bit, it is easy to get an infinite loop:


    public static int sizeOfEncodedInteger(int value) {
        int contentLength = 0;
        do {
            value >>= 8;
            contentLength++;
        } while (value != 0);
        return contentLength;
    }


    sizeOfEncodedInteger(result); // can infinite loop
    sizeOfEncodedInteger(resultBounded); // cannot infinite loop