Java Random Int randomByteArray(int length)

Here you can find the source of randomByteArray(int length)

Description

Create an array of random bytes

License

Open Source License

Parameter

Parameter Description
length The length of the created array

Return

the byte array

Declaration

public static byte[] randomByteArray(int length) 

Method Source Code

//package com.java2s;
/*//from ww w .ja v  a  2  s  .  c  o m
 *
 *  Copyright 2014 Red Hat, Inc.
 *
 *  All rights reserved. This program and the accompanying materials
 *  are made available under the terms of the Eclipse Public License v1.0
 *  and Apache License v2.0 which accompanies this distribution.
 *
 *      The Eclipse Public License is available at
 *      http://www.eclipse.org/legal/epl-v10.html
 *
 *      The Apache License v2.0 is available at
 *      http://www.opensource.org/licenses/apache2.0.php
 *
 *  You may elect to redistribute this code under either of these licenses.
 *
 *
 */

public class Main {
    /**
     * Create an array of random bytes
     *
     * @param length The length of the created array
     * @return the byte array
     */
    public static byte[] randomByteArray(int length) {
        return randomByteArray(length, false, (byte) 0);
    }

    /**
     * Create an array of random bytes
     *
     * @param length    The length of the created array
     * @param avoid     If true, the resulting array will not contain avoidByte
     * @param avoidByte A byte that is not to be included in the resulting array
     * @return an array of random bytes
     */
    public static byte[] randomByteArray(int length, boolean avoid, byte avoidByte) {
        byte[] line = new byte[length];
        for (int i = 0; i < length; i++) {
            byte rand;
            do {
                rand = randomByte();
            } while (avoid && rand == avoidByte);

            line[i] = rand;
        }
        return line;
    }

    /**
     * @return a random byte
     */
    public static byte randomByte() {
        return (byte) ((int) (Math.random() * 255) - 128);
    }
}

Related

  1. randomAlphaString(int length)
  2. randomArray(int len)
  3. randomArray(int min, int max, int n)
  4. randomBases(int n)
  5. randomBlock(byte[] block, int off, int len)
  6. randomByteArray(int size, byte from, byte to)
  7. randomByteAsInt()
  8. randomBytes(int size)
  9. randomBytes(int size)