Logo

Programming-Idioms

  • C++
  • Ruby
  • Scheme
  • Go

Idiom #310 Fill array with random bytes

Fill the byte array a with randomly generated bytes.

import "crypto/rand"
_, err := rand.Read(a)

The package crypto/rand is secure (but slower than math/rand)
require 'securerandom'
a = SecureRandom.random_bytes(a.length)
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...
< >
programming-idioms.org