Logo

Programming-Idioms

  • Lisp
  • C++
  • PHP
  • Java
  • Python
  • JS
  • Clojure
  • Perl

Idiom #310 Fill array with random bytes

Fill the byte array a with randomly generated bytes.

my $n = 20;

my $bytestring;
foreach my $i (0 .. $n*8 - 1) {
    vec($bytestring, $i, 1) = rand(2);
}

Use perl builtin vec() function to set bits by indexing into a scalar. Perl will add bytes to the string as needed - which means the actual bitcount will always be in increments of 8.
use Bytes::Random;
my $s = random_bytes( $number_of_bytes );
my @a = split //, $s;

Perl doesn't have byte arrays per se. Bytes::Random from CPAN will generate a string of random bytes. Splitting that on an empty regex in list context will return the bytes in a list.
import java.util.Random;
new Random().nextBytes(a);

For performance, consider reusing the Random instance
import random
a[:] = random.randbytes(len(a))

If array a exists and its content is to be replaced.
import random
a = random.randbytes(N)

Create a new array a with N bytes.
use, intrinsic:: iso_fortran_env, only: int8
  real, dimension(100) :: b
  integer(int8), dimension(100) :: a
  call random_number(b)
  a = b*256 - 128

Fortran has no "byte" type per se, but it has (if supported) an integer type with 8 bits, which has the kind from iso_fortran_env. The intrinsic subroutine random_number returns random numbers in the range of [0..1[.

New implementation...