Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!

Idiom #310 Fill array with random bytes

Fill the byte array a with randomly generated bytes.

use rand::prelude::*;
let mut rng = rand::thread_rng();
rng.fill(&mut a);
use, intrinsic:: iso_fortran_env, only: int8
  real, dimension(100) :: b
  integer(int8), dimension(100) :: a
  call random_number(b)
  a = b*256 - 128
import "crypto/rand"
_, err := rand.Read(a)
import java.util.Random;
new Random().nextBytes(a);
for b in a do b := random(256);
use Bytes::Random;
my $s = random_bytes( $number_of_bytes );
my @a = split //, $s;
my $n = 20;

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

import random
a[:] = random.randbytes(len(a))
import random
a = random.randbytes(N)
require 'securerandom'
a = SecureRandom.random_bytes(a.length)

New implementation...
< >
programming-idioms.org