Home / cs-notes / Language / Java / Basic / Math / Random / nextBytes
/**
* Generates random bytes and places them into a user-supplied
* byte array. The number of random bytes produced is equal to
* the length of the byte array.
*
* <p>The method {@code nextBytes} is implemented by class {@code Random}
* as if by:
* <pre> {@code
* public void nextBytes(byte[] bytes) {
* for (int i = 0; i < bytes.length; )
* for (int rnd = nextInt(), n = Math.min(bytes.length - i, 4);
* n-- > 0; rnd >>= 8)
* bytes[i++] = (byte)rnd;
* }}</pre>
*
* @param bytes the byte array to fill with random bytes
* @throws NullPointerException if the byte array is null
* @since 1.1
*/
public void nextBytes(byte[] bytes) {
for (int i = 0, len = bytes.length; i < len; )
for (int rnd = nextInt(),
n = Math.min(len - i, Integer.SIZE/Byte.SIZE);
n-- > 0; rnd >>= Byte.SIZE)
bytes[i++] = (byte)rnd;
}