mercredi 19 avril 2017

Why does ThreadLocalRandom.current().nextInt(1, 255); return values outside of the range [1, 254]?

I am trying to generate a random positive 8-bit integer. The documentation for ThreadLocalRandom.current().nextInt(min, max) specifically says that min is the minimum inclusive bound, and max is the maximum exclusive bound. However, if I set max to any value > 128, I will occasionally get a negative value.

This seems to be associated with the bits of an integer, but the documentation says nothing about bits for nextInt(). I really need as many positive 8-bit numbers as I can get. Why is nextInt() returning negative values when I only specify a positive range of (1, 255)?

byte aa = 1;
    do {
            aa = (byte) ThreadLocalRandom.current().nextInt(1, 128);
    } while (aa > 0);
    System.out.println(aa);

Aucun commentaire:

Enregistrer un commentaire