Random number generator (device): Difference between revisions

added RPL
(added RPL)
 
(79 intermediate revisions by 46 users not shown)
Line 1:
{{task}}[[Category:Input Output]]
[[Category:Input Output]]
 
;Task:
If your system has a means to generate random numbers involving not only a software algorithm (like the [[wp:/dev/random|/dev/urandom]] devices in Unix), show how to obtain a random 32-bit number from that mechanism.
If your system has a means to generate random numbers involving not only a software algorithm   (like the [[wp:/dev/random|/dev/urandom]] devices in Unix),   then:
 
show how to obtain a random 32-bit number from that mechanism.
 
;Related task
* [[Random_number_generator_(included)]]
<br><br>
 
=={{header|AArch64 Assembly}}==
 
{{works with|aarch64-linux-gnu-as/qemu-aarch64}}
 
Linux provides <code>getrandom</code> syscall for most architectures, which draws random bytes from <code>/dev/urandom</code> by default.
 
The syscall number on AArch64 is 278.
 
<syntaxhighlight lang="arm_assembly">.equ STDOUT, 1
.equ SVC_WRITE, 64
.equ SVC_GETRANDOM, 278
.equ SVC_EXIT, 93
 
.text
.global _start
 
_start:
stp x29, x30, [sp, -32]! // allocate buffer space at [sp]
mov x29, sp
mov x0, sp
mov x1, #4
bl _getrandom // getrandom(&tmp, 4);
ldr w0, [sp]
bl print_uint64 // print_uint64(tmp);
ldp x29, x30, [sp], 32
mov x0, #0
b _exit // exit(0);
 
// void print_uint64(uint64_t x) - print an unsigned integer in base 10.
print_uint64:
// x0 = remaining number to convert
// x1 = pointer to most significant digit
// x2 = 10
// x3 = x0 / 10
// x4 = x0 % 10
// compute x0 divmod 10, store a digit, repeat if x0 > 0
ldr x1, =strbuf_end
mov x2, #10
1: udiv x3, x0, x2
msub x4, x3, x2, x0
add x4, x4, #48
mov x0, x3
strb w4, [x1, #-1]!
cbnz x0, 1b
// compute the number of digits to print, then call write()
ldr x3, =strbuf_end_newline
sub x2, x3, x1
mov x0, #STDOUT
b _write
 
.data
strbuf:
.space 31
strbuf_end:
.ascii "\n"
strbuf_end_newline:
.align 4
 
.text
//////////////// system call wrappers
// ssize_t _write(int fd, void *buf, size_t count)
_write:
mov x8, #SVC_WRITE
svc #0
ret
 
// ssize_t getrandom(void *buf, size_t buflen, unsigned int flags=0)
_getrandom:
mov x2, #0
mov x8, #SVC_GETRANDOM
svc #0
ret
 
// void _exit(int retval)
_exit:
mov x8, #SVC_EXIT
svc #0</syntaxhighlight>
 
=={{header|Ada}}==
random.adb:
<langsyntaxhighlight Adalang="ada">with Ada.Streams.Stream_IO;
with Ada.Text_IO;
procedure Random is
Line 17 ⟶ 103:
Ada.Streams.Stream_IO.Close (Random_File);
Ada.Text_IO.Put_Line ("Number:" & Integer'Image (Number));
end Random;</langsyntaxhighlight>
 
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang="arm assembly">
 
/* ARM assembly Raspberry PI */
/* program urandom.s */
 
/* Constantes */
.equ STDOUT, 1 @ Linux output console
.equ EXIT, 1 @ Linux syscall
.equ READ, 3
.equ WRITE, 4
.equ OPEN, 5
.equ CLOSE, 6
 
.equ O_RDONLY, 0 @ open for reading only
 
.equ BUFFERSIZE, 4 @ random number 32 bits
 
/* Initialized data */
.data
szFileName: .asciz "/dev/urandom" @ see linux doc
szCarriageReturn: .asciz "\n"
/* datas error display */
szMessErreur: .asciz "Error detected.\n"
szMessErr: .ascii "Error code hexa : "
sHexa: .space 9,' '
.ascii " decimal : "
sDeci: .space 15,' '
.asciz "\n"
/* datas message display */
szMessResult: .ascii "Random number :"
sValue: .space 12,' '
.asciz "\n"
/* UnInitialized data */
.bss
sBuffer: .skip BUFFERSIZE @ buffer result
 
/* code section */
.text
.global main
main:
ldr r0,iAdrszFileName @ File name
mov r1,#O_RDONLY @ flags
mov r2,#0 @ mode
mov r7,#OPEN @ open file
svc #0
cmp r0,#0 @ error ?
ble error
mov r8,r0 @ save FD
mov r4,#0 @ loop counter
1:
mov r0,r8 @ File Descriptor
ldr r1,iAdrsBuffer @ buffer address
mov r2,#BUFFERSIZE @ buffer size
mov r7,#READ @ call system read file
svc 0
cmp r0,#0 @ read error ?
ble error
ldr r1,iAdrsBuffer @ buffer address
ldr r0,[r1] @ display buffer value
ldr r1,iAdrsValue
bl conversion10
ldr r0,iAdrszMessResult
bl affichageMess
add r4,#1 @ increment counter
cmp r4,#10 @ maxi ?
blt 1b @ no -> loop
 
 
end:
mov r0,r8
mov r7, #CLOSE @ call system close file
svc #0
cmp r0,#0
blt error
mov r0,#0 @ return code
b 100f
error:
ldr r1,iAdrszMessErreur @ error message
bl displayError
mov r0,#1 @ return error code
100: @ standard end of the program
mov r7, #EXIT @ request to exit program
svc 0 @ perform system call
iAdrsBuffer: .int sBuffer
iAdrsValue: .int sValue
iAdrszMessResult: .int szMessResult
iAdrszFileName: .int szFileName
iAdrszMessErreur: .int szMessErreur
iAdrszCarriageReturn: .int szCarriageReturn
 
/******************************************************************/
/* display text with size calculation */
/******************************************************************/
/* r0 contains the address of the message */
affichageMess:
push {r0,r1,r2,r7,lr} @ save registers
mov r2,#0 @ counter length */
1: @ loop length calculation
ldrb r1,[r0,r2] @ read octet start position + index
cmp r1,#0 @ if 0 its over
addne r2,r2,#1 @ else add 1 in the length
bne 1b @ and loop
@ so here r2 contains the length of the message
mov r1,r0 @ address message in r1
mov r0,#STDOUT @ code to write to the standard output Linux
mov r7, #WRITE @ code call system "write"
svc #0 @ call system
pop {r0,r1,r2,r7,lr} @ restaur registers
bx lr @ return
/***************************************************/
/* display error message */
/***************************************************/
/* r0 contains error code r1 : message address */
displayError:
push {r0-r2,lr} @ save registers
mov r2,r0 @ save error code
mov r0,r1
bl affichageMess
mov r0,r2 @ error code
ldr r1,iAdrsHexa
bl conversion16 @ conversion hexa
mov r0,r2 @ error code
ldr r1,iAdrsDeci @ result address
bl conversion10S @ conversion decimale
ldr r0,iAdrszMessErr @ display error message
bl affichageMess
100:
pop {r0-r2,lr} @ restaur registers
bx lr @ return
iAdrszMessErr: .int szMessErr
iAdrsHexa: .int sHexa
iAdrsDeci: .int sDeci
/******************************************************************/
/* Converting a register to hexadecimal */
/******************************************************************/
/* r0 contains value and r1 address area */
conversion16:
push {r1-r4,lr} @ save registers
mov r2,#28 @ start bit position
mov r4,#0xF0000000 @ mask
mov r3,r0 @ save entry value
1: @ start loop
and r0,r3,r4 @ value register and mask
lsr r0,r2 @ move right
cmp r0,#10 @ compare value
addlt r0,#48 @ <10 ->digit
addge r0,#55 @ >10 ->letter A-F
strb r0,[r1],#1 @ store digit on area and + 1 in area address
lsr r4,#4 @ shift mask 4 positions
subs r2,#4 @ counter bits - 4 <= zero ?
bge 1b @ no -> loop
 
100:
pop {r1-r4,lr} @ restaur registers
bx lr
/***************************************************/
/* Converting a register to a signed decimal */
/***************************************************/
/* r0 contains value and r1 area address */
conversion10S:
push {r0-r4,lr} @ save registers
mov r2,r1 @ debut zone stockage
mov r3,#'+' @ par defaut le signe est +
cmp r0,#0 @ negative number ?
movlt r3,#'-' @ yes
mvnlt r0,r0 @ number inversion
addlt r0,#1
mov r4,#10 @ length area
1: @ start loop
bl divisionpar10U
add r1,#48 @ digit
strb r1,[r2,r4] @ store digit on area
sub r4,r4,#1 @ previous position
cmp r0,#0 @ stop if quotient = 0
bne 1b
 
strb r3,[r2,r4] @ store signe
subs r4,r4,#1 @ previous position
blt 100f @ if r4 < 0 -> end
 
mov r1,#' ' @ space
2:
strb r1,[r2,r4] @store byte space
subs r4,r4,#1 @ previous position
bge 2b @ loop if r4 > 0
100:
pop {r0-r4,lr} @ restaur registers
bx lr
/***************************************************/
/* division par 10 unsigned */
/***************************************************/
/* r0 dividende */
/* r0 quotient */
/* r1 remainder */
divisionpar10U:
push {r2,r3,r4, lr}
mov r4,r0 @ save value
//mov r3,#0xCCCD @ r3 <- magic_number lower raspberry 3
//movt r3,#0xCCCC @ r3 <- magic_number higter raspberry 3
ldr r3,iMagicNumber @ r3 <- magic_number raspberry 1 2
umull r1, r2, r3, r0 @ r1<- Lower32Bits(r1*r0) r2<- Upper32Bits(r1*r0)
mov r0, r2, LSR #3 @ r2 <- r2 >> shift 3
add r2,r0,r0, lsl #2 @ r2 <- r0 * 5
sub r1,r4,r2, lsl #1 @ r1 <- r4 - (r2 * 2) = r4 - (r0 * 10)
pop {r2,r3,r4,lr}
bx lr @ leave function
iMagicNumber: .int 0xCCCCCCCD
 
</syntaxhighlight>
 
=={{header|Batch File}}==
The dynamic environmental variable <code>%random%</code> contains a number between 0 and 32767.
<syntaxhighlight lang="dos">
@echo %random%
</syntaxhighlight>
 
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
Requires Windows XP or later.
<langsyntaxhighlight lang="bbcbasic"> SYS "SystemFunction036", ^random%, 4
PRINT ~random%</langsyntaxhighlight>
 
=={{header|C}}==
It works on systems having /dev/urandom, like [[GNU]]/[[Linux]].
 
<langsyntaxhighlight lang="c">#include <inttypesstdio.h>
#include <stdiostdlib.h>
#include <stdint.h>
 
#define RANDOM_PATH "/dev/urandom"
int main(int argc, char **argv)
 
int main(void)
{
unsigned char buf[4];
uint32_t v;
unsigned long v;
FILE *r = fopen("/dev/urandom", "r");
if (r == NULL) FILE *fin;
{
perror("/dev/urandom");
return 1;
}
 
size_t br = fread if (&v,(fin sizeof= v, 1fopen(RANDOM_PATH, "r");) == NULL) {
fprintf(stderr, "%s: unable to open file\n", RANDOM_PATH);
if (br < 1)
return EXIT_FAILURE;
{
}
fputs("/dev/urandom: Not enough bytes\n", stderr);
if (fread(buf, 1, sizeof buf, fin) != sizeof buf) {
return 1;
fprintf(stderr, "%s: not enough bytes (expected %u)\n",
}
RANDOM_PATH, (unsigned) sizeof buf);
 
return EXIT_FAILURE;
printf("%" PRIu32 "\n", v);
fclose(r); }
return 0 fclose(fin);
v = buf[0] | buf[1] << 8UL | buf[2] << 16UL | buf[3] << 24UL;
}</lang>
printf("%lu\n", v);
return 0;
}</syntaxhighlight>
 
=== {{libheader|BSD libc}} ===
[http://www.openbsd.org/cgi-bin/man.cgi?query=arc4random&apropos=0&sektion=3&manpath=OpenBSD+Current&arch=i386&format=html arc4random()] appeared in [[OpenBSD]] 2.1 and has spread to many [[BSD]] systems. This function runs an ARC4 random number generator that takes entropy from a kernel device. (This kernel device is sysctl kern.arandom in OpenBSD, or /dev/urandom in some other systems.)
 
<langsyntaxhighlight lang="c">#include <inttypes.h> /* PRIu32 */
#include <stdlib.h> /* arc4random */
#include <stdio.h> /* printf */
Line 65 ⟶ 370:
printf("%" PRIu32 "\n", arc4random());
return 0;
}</langsyntaxhighlight>
 
=== {{libheader|OpenSSL}} ===
OpenSSL can generate random numbers. The default generator uses SHA1. For [[Unix]] systems, OpenSSL will gather entropy by reading a kernel device like /dev/urandom, or by using [http://egd.sourceforge.net/ EGD, the Entropy Gathering Daemon]. For other systems, OpenSSL might use a different source of entropy.
 
<langsyntaxhighlight lang="c">#include <inttypes.h>
#include <stdio.h>
 
Line 87 ⟶ 392:
printf("%" PRIu32 "\n", v);
return 0;
}</langsyntaxhighlight>
 
=== Windows ===
{{works with|MinGW}}
 
<langsyntaxhighlight lang="c">#include <stdio.h> /* printf */
#include <windows.h>
#include <wincrypt.h> /* CryptAcquireContext, CryptGenRandom */
Line 114 ⟶ 419:
CryptReleaseContext(p, 0);
return 0;
}</langsyntaxhighlight>
=== debian/linux made from scratch ===
{{works with|GCC}}
<syntaxhighlight lang="c">
#include <stdio.h>
#include <stdlib.h>
 
/*
== {{header|C++}} ==
(C) 2020 J.G.A. Debaere, all rights reserved 2020/10/29
 
Put into Public Domain for individuals only
Tested with NIST, Diehard, Diehard 3.31
gcc -lm ./jpsrand_f.c -o ./jpsrand_f.o
 
dieharder -a -f /tmp/tmp.bin
 
I consider it TRNG,
using Time, Hardddisk and Memory as the hardware component
 
No warranty of any kind, "AS IS"
Last time I tested ( 2021/07/07 ) with dieharder:
rgb_bitdist | 8| 100000| 100|0.99716738| WEAK
rgb_lagged_sum | 3| 1000000| 100|0.99661184| WEAK
Out of 114 tests, rest PASSED
 
Obviously, it changes per run :)
*/
 
unsigned int jps_rand()
{
/* (C) 2020 J.G.A. Debaere, all rights reserved */
#include <dirent.h>
 
#include <sys/time.h>
 
struct timeval current_time ;
DIR *folder ;
struct dirent *en ;
folder = opendir ( "." ) ;
 
while ( ( folder ) && ( en = readdir ( folder ) ) != NULL )
 
asm ( "nop" ) ;
closedir ( folder ) ;
gettimeofday( &current_time, NULL ) ;
unsigned int t = ( current_time.tv_sec * current_time.tv_usec / 17.17 ) ;
return t ;
}
 
int main()
{
FILE * f1;
 
f1 = fopen("/tmp/tmp.bin", "wb");
 
 
unsigned int t = ( unsigned int ) jps_rand() ;
for ( unsigned int k = 0; k < 40000000 ; k++ )
{
t = jps_rand () ;
 
fwrite ( &t, sizeof( unsigned int ), 1, f1 ) ;
}
fflush(f1);
fclose(f1);
return 0;
}
 
</syntaxhighlight>
 
JPD 2021/07/07
 
Output:
 
Random
 
=={{header|C++}}==
<code>std::random_device</code> is a uniformly-distributed integer random number generator that produces non-deterministic random numbers.
 
Line 123 ⟶ 521:
See the C++ section on [[Random_number_generator_(included)#C.2B.2B|Random number generator (included)]] for the list of pseudo-random number engines available.
{{works with|C++11}}
<langsyntaxhighlight lang="cpp">#include <iostream>
#include <string>
#include <random>
Line 130 ⟶ 527:
{
std::random_device rd;
std::uniform_int_distribution<intlong> dist; // long is guaranteed to be 32 bits
std::cout << "Random Number: " << dist(rd) << std::endl;
}</langsyntaxhighlight>
 
=={{header|C sharp}}==
<langsyntaxhighlight lang="csharp">using System;
using System.Security.Cryptography;
 
Line 149 ⟶ 546:
 
return result;
}</langsyntaxhighlight>
 
Park-Miller random number generator
<syntaxhighlight lang="csharp">
const long m = 2147483647L;
const long a = 48271L;
const long q = 44488L;
const long r = 3399L;
static long r_seed = 12345678L;
 
public static byte gen()
{
long hi = r_seed / q;
long lo = r_seed - q * hi;
long t = a * lo - r * hi;
if (t > 0)
r_seed = t;
else
r_seed = t + m;
return (byte)r_seed;
}
 
public static void ParkMiller(byte[] arr)
{
byte[] arr = new byte[10900000];
for (int i = 0; i < arr.Length; i++)
{
arr[i] = gen();
}
}</syntaxhighlight>
 
=={{header|ChucK}}==
<syntaxhighlight lang="c"> Math.random2(-(Math.random()),Math.random(); </syntaxhighlight>
 
=={{header|Common Lisp}}==
<syntaxhighlight lang="lisp">(defun random-int32 ()
(with-open-file (s "/dev/random" :element-type '(unsigned-byte 32))
(read-byte s)))</syntaxhighlight>
 
=={{header|D}}==
Example of MersenneTwisterEngine for generating uniformly-distributed 32-bit numbers with a period of 2 to the power of 19937.
<syntaxhighlight lang="d">
import std.stdio;
import std.random;
 
void main()
{
Mt19937 gen;
gen.seed(unpredictableSeed);
auto n = gen.front;
writeln(n);
}
</syntaxhighlight>
 
{{out}}
<pre>
run 1: 3500391376
run 2: 9537841895
run 3: 1588499117
run 4: ...
</pre>
=={{header|Delphi}}==
==={{header|Windows}}===
{{libheader| System.SysUtils}}
{{libheader| Winapi.WinCrypt}}[[https://github.com/magicxor/WinCryptographyAPIs]]
<syntaxhighlight lang="delphi">
program Random_number_generator;
 
{$APPTYPE CONSOLE}
 
uses
System.SysUtils,
Winapi.WinCrypt;
 
var
hCryptProv: NativeUInt;
i: Byte;
UserName: PChar;
 
function Random: UInt64;
var
pbData: array[0..7] of byte;
i: integer;
begin
if not CryptGenRandom(hCryptProv, 8, @pbData[0]) then
exit(0);
Result := 0;
for i := 0 to 7 do
Result := Result + (pbData[i] shl (8 * i));
end;
 
procedure Randomize;
begin
CryptAcquireContext(hCryptProv, UserName, nil, PROV_RSA_FULL, 0);
end;
 
begin
Randomize;
for i := 0 to 9 do
Writeln(Random);
Readln;
end.</syntaxhighlight>
{{out}}
<pre>6246170830
2020144138
5469928375
5580575688
3947181392
4671237100
4269461866
4842880207
4217687233
1714028876</pre>
==={{header|Linux}}===
See [[#Pascal]].
=={{header|EchoLisp}}==
No random device provided by the host (browser). But we can use the system timer to get a physical input.
<syntaxhighlight lang="lisp">
(random-seed "simon")
(random (expt 2 32)) → 2275215386
(random-seed "simon")
(random (expt 2 32)) → 2275215386 ;; the same
 
 
(random-seed (current-time-milliseconds ))
(random (expt 2 32)) → 4061857345
(random-seed (current-time-milliseconds ))
(random (expt 2 32)) → 1322611152
</syntaxhighlight>
 
=={{header|Factor}}==
Factor has good support for switching between different random number generators. <code>with-system-random</code> is a combinator that encapsulates the task of using a system RNG (/dev/random in the case of GNU/Linux).
<syntaxhighlight lang="factor">USE: random
[ random-32 ] with-system-random .</syntaxhighlight>
 
=={{header|Forth}}==
<langsyntaxhighlight lang="forth">variable rnd
 
: randoms ( n -- )
Line 160 ⟶ 690:
rnd @ .
loop
close-file throw ;</langsyntaxhighlight>
 
=={{header|Fortran}}==
Using system /dev/urandom in [[GNU]]/[[Linux]].
 
<syntaxhighlight lang="fortran">
!-----------------------------------------------------------------------
! Test Linux urandom in Fortran
!-----------------------------------------------------------------------
program urandom_test
use iso_c_binding, only : c_long
implicit none
 
character(len=*), parameter :: RANDOM_PATH = "/dev/urandom"
integer :: funit, ios
integer(c_long) :: buf
 
open(newunit=funit, file=RANDOM_PATH, access="stream", form="UNFORMATTED", &
iostat=ios, status="old", action="read")
if ( ios /= 0 ) stop "Error opening file: "//RANDOM_PATH
 
read(funit) buf
 
close(funit)
 
write(*,'(A,I64)') "Integer: ", buf
write(*,'(A,B64)') "Binary: ", buf
write(*,'(A,Z64)') "Hexadecimal: ", buf
 
end program urandom_test
</syntaxhighlight>
 
Here's an example of the use of the latter:
 
=={{header|FreeBASIC}}==
FreeBASIC can in theory use any C library to produce pseudo-random numbers including those which are partly device based.
 
However, in practice, there is little need for this as specifying a second parameter of 5 to FB's Randomize statement produces cryptographically strong pseudo-random numbers using either the Win32 Crypto API or the /dev/urandom device under Linux.
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
Randomize , 5
 
'generate 10 cryptographic random integers in the range 1 To 100
For i As Integer = 1 To 10
Print Int(Rnd * 100) + 1
Next
 
Sleep</syntaxhighlight>
 
 
=={{header|FutureBasic}}==
FB offers a variety of ways to generate random numbers of varying degrees of distribution and randomness accuracy. In addition to its native rnd() function which returns random integers from 1 and higher, it can also access any C library function, i.e, rand(), arc4random, arc4random_uniform, as well as random number generators in Apple's GameplayKit library. Here are a few examples:
<syntaxhighlight lang="freebasic">
include "Tlbx GameplayKit.incl"
 
local fn RandomBigInteger( digits as UInt64 ) as UInt64
end fn = fn GKLinearCongruentialRandomSourceSeed( fn GKLinearCongruentialRandomSourceInit ) mod digits
 
local fn RandomIntegerInRange( min as UInt64, max as UInt64 ) as UInt64
UInt64 rndIntInRange = fn RandomBigInt( max - min + 1 ) + min - 1
end fn = rndIntInRange
 
local fn ArcRandomIntegerInRage( min as long, max as long ) as long
long i
cln i = (arc4random()%(max-min+1))+min;
end fn = fn floor(i)
 
// Returns double in range of 0.0 to 50.0
double r
cln r = (((double)arc4random()/0x100000000)*50);
 
randomInteger = rnd(expr%)
</syntaxhighlight>
 
 
=={{header|GlovePIE}}==
<syntaxhighlight lang="glovepie">var.rand=random(10)</syntaxhighlight>
 
=={{header|Go}}==
In the Go library is crypto/rand, a source specified to use dev/urandom on Unix-like systems and the CryptGenRandom API on Windows. Also implemented here is a source using dev/random, if you really want it. On my system it would print a few numbers then hang until I moved the mouse or pressed some keys on the keyboard.
<langsyntaxhighlight lang="go">package main
 
import (
Line 196 ⟶ 803:
}
fmt.Println()
}</langsyntaxhighlight>
 
=={{header|Groovy}}==
Based, necessarily, on Java solution:
<langsyntaxhighlight lang="groovy">def rng = new java.security.SecureRandom()</langsyntaxhighlight>
 
Test:
<langsyntaxhighlight lang="groovy">(0..4).each { println rng.nextInt() }</langsyntaxhighlight>
 
{{out}}
Output:
<pre>380425053
-1003791794
Line 211 ⟶ 818:
1152610574
714616658</pre>
 
=={{header|Haskell}}==
{{libheader|Entropy}}
{{Works with|GHC|7.4.1}}
<syntaxhighlight lang="haskell">#!/usr/bin/env runhaskell
 
import System.Entropy
import Data.Binary.Get
import qualified Data.ByteString.Lazy as B
 
main = do
bytes <- getEntropy 4
print (runGet getWord32be $ B.fromChunks [bytes])</syntaxhighlight>
 
=={{header|Icon}} and {{header|Unicon}}==
Line 216 ⟶ 836:
The following is Unicon-specific but trivially converted into Icon.
 
<langsyntaxhighlight lang="unicon">procedure main(A)
n := integer(A[1])|5
every !n do write(rand(4))
Line 227 ⟶ 847:
close(f)
return x
end</langsyntaxhighlight>
 
Sample runs:
Line 243 ⟶ 863:
 
Untested:
<langsyntaxhighlight lang="j">256#.a.i.1!:11'/dev/urandom';0 4</langsyntaxhighlight>
 
Fallback:
<langsyntaxhighlight lang="j">256#.a.i.4{.host'dd if=/dev/urandom bs=4 count=1'</langsyntaxhighlight>
 
Note: this assumes that J is running on linux.
 
=={{header|Java}}==
<langsyntaxhighlight lang="java">import java.security.SecureRandom;
 
public class RandomExample {
Line 260 ⟶ 880:
System.out.println(rng.nextInt());
}
}</langsyntaxhighlight>
 
=={{header|HaskellJoy}}==
<syntaxhighlight lang="joy">DEFINE sysrand32 ==
{{Works with|GHC|7.4.1}}
"/dev/urandom" "r" fopen dup 4 fread swap fclose unswons [swap 256 * +] fold.</syntaxhighlight>
<lang haskell>#!/usr/bin/runhaskell
 
=={{header|jq}}==
import System.Entropy
jq does not provide direct access to /dev/urandom but it is quite straightforward to do so.
import Data.Binary.Get
We consider two cases: uniform distribution on the interval [0,1] and on the set of non-negative integers less than a given N.
import qualified Data.ByteString.Lazy as B
 
===Uniform distribution on an interval===
main = do
We assume the availability of `od`, `tr`, and `fold`, and illustrate how to produce an indefinitely long stream of pseudo-random numbers that are approximately uniformly distributed in the range [0,1].
bytes <- getEntropy 4
 
print (runGet getWord32be $ B.fromChunks [bytes])</lang>
Assuming the jq program shown below is in a file named uniform.jq, the command-line invocation would be:
<pre>od -t x -An /dev/urandom | tr -d " " | fold -w 8 | jq -R -f uniform.jq</pre>
 
<syntaxhighlight lang="jq"># allow both upper and lower-case characters
def hex2integer:
explode
| reverse
| map(if . > 96 then . - 87 elif . > 64 then . - 55 else . - 48 end)
| reduce .[] as $c
# state: [power, ans]
([1,0]; (.[0] * 16) as $b | [$b, .[1] + (.[0] * $c)])
| .[1];
 
select(length>0) | hex2integer / pow(16;length)</syntaxhighlight>
 
Notice that the program automatically adjusts the precision based on the length of the hexadecimal numbers presented. Since jq uses IEEE 754 64-bit arithmetic, specifying a larger value to `fold`, such as 10, will produce more precise results.
 
===Uniform distribution on a range of integers===
<syntaxhighlight lang="sh">< /dev/random tr -cd '0-9' | fold -w 1 | jq -Mn '
 
# Output: a PRN in range(0;$n) where $n is .
def prn:
if . == 1 then 0
else . as $n
| (($n-1)|tostring|length) as $w
| [limit($w; inputs)] | join("") | tonumber
| if . < $n then . else ($n | prn) end
end;
 
100 | prn
'</syntaxhighlight>
 
=={{header|Julia}}==
{{works with|Linux}}
<syntaxhighlight lang="julia">
const rdev = "/dev/random"
rstream = try
open(rdev, "r")
catch
false
end
 
if isa(rstream, IOStream)
b = readbytes(rstream, 4)
close(rstream)
i = reinterpret(Int32, b)[1]
println("A hardware random number is: ", i)
else
println("The hardware random number stream, ", rdev, ", was unavailable.")
end
</syntaxhighlight>
 
{{out}}
<pre>
A hardware random number is: 986109744
</pre>
 
=={{header|Kotlin}}==
<syntaxhighlight lang="scala">// version 1.1.2
 
import java.security.SecureRandom
 
fun main(args: Array<String>) {
val rng = SecureRandom()
val rn1 = rng.nextInt()
val rn2 = rng.nextInt()
val newSeed = rn1.toLong() * rn2
rng.setSeed(newSeed) // reseed using the previous 2 random numbers
println(rng.nextInt()) // get random 32-bit number and print it
}</syntaxhighlight>
 
=={{header|Lasso}}==
<langsyntaxhighlight lang="lasso">file(`/dev/urandom`)->readSomeBytes(4)->export32bits</langsyntaxhighlight>
{{out}}
<pre>723217350</pre>
 
=={{header|M2000 Interpreter}}==
<syntaxhighlight lang="m2000 interpreter">
Module checkit {
Declare random1 lib "advapi32.SystemFunction036" {long lpbuffer, long length}
Buffer Clear Alfa as long*2
Print Eval(Alfa,0)
Print Eval(Alfa,1)
call void random1(alfa(0), 8)
Print Eval(Alfa,0)
Print Eval(Alfa,1)
}
checkit
</syntaxhighlight>
 
 
<syntaxhighlight lang="m2000 interpreter">
Function Random2 {
Declare CryptAcquireContext Lib "advapi32.CryptAcquireContextW" {long ByRefhProv, pszContainer$,pszProvider$, long dwProvType, long dwFlags}
Declare CryptReleaseContext Lib "advapi32.CryptReleaseContext" {Long hProv, Long dwFlags}
Declare CryptGenRandom Lib "advapi32.CryptGenRandom" {Long hProv, Long dwLen, Long ByRef}
Const PROV_RSA_FULL As Long = 1
Const VERIFY_CONTEXT As Long = 0xF0000000&
Buffer Clear RandomNum as Long
Buffer Clear hProv as long
Call Void CryptAcquireContext( hProv(0), "", "", PROV_RSA_FULL, VERIFY_CONTEXT)
Call Void CryptGenRandom( Eval(hProv,0), 4, RandomNum(0))
Call Void CryptReleaseContext(Eval(hProv,0), 0&)
=Eval(RandomNum,0)
}
Print Random2()
</syntaxhighlight>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<syntaxhighlight lang="mathematica">rand32[] := RandomInteger[{-2^31, 2^31 - 1}]</syntaxhighlight>
Example: create array of 10 rand32 numbers
<syntaxhighlight lang="mathematica">Table[rand32[], {i, 1, 10}]</syntaxhighlight>
{{out}}
<pre>{355587317, -869860319, -91421859, 1605907693, 101463390, 891823090,
-531713717, -1038608428, 1717313407, 674189312}</pre>
 
=={{header|Mercury}}==
For versions of Mercury greater than 20.06, the standard library module <tt>random.system_rng</tt> provides access to a platform specific random data source.<br />
 
Generates unsigned 32-bit integers.
 
<syntaxhighlight lang="mercury">:- module random_number_device.
:- interface.
 
:- import_module io.
:- pred main(io::di, io::uo) is det.
 
:- implementation.
:- import_module maybe, random, random.system_rng, require.
 
main(!IO) :-
open_system_rng(MaybeRNG, !IO),
(
MaybeRNG = ok(RNG),
random.generate_uint32(RNG, U32, !IO),
io.print_line(U32, !IO),
close_system_rng(RNG, !IO)
;
MaybeRNG = error(ErrorMsg),
io.stderr_stream(Stderr, !IO),
io.print_line(Stderr, ErrorMsg, !IO),
io.set_exit_status(1, !IO)
).</syntaxhighlight>
 
=={{header|NetRexx}}==
{{Works with|Mac OS X}} and probably other UNIX systems that provide <tt>/dev/random</tt> or <tt>/dev/urandom</tt> random data source devices.<br />
<langsyntaxhighlight NetRexxlang="netrexx">/* NetRexx */
options replace format comments java crossref savelog symbols binary
 
Line 313 ⟶ 1,071:
for ((i=0; i<10; ++i)); do java <program_name>; done # Shell loop to run the command 10 times
*/
</syntaxhighlight>
</lang>
{{out}}
'''Output:'''
<pre>
$ for ((i=0; i<10; ++i)); do java RRandomGen; done # Shell loop to run the command 10 times
Line 329 ⟶ 1,087:
$
</pre>
 
=={{header|Nim}}==
<syntaxhighlight lang="nim">var f = open("/dev/urandom")
var r: int32
discard f.readBuffer(addr r, 4)
close(f)
echo r</syntaxhighlight>
 
=={{header|OCaml}}==
 
OCaml's default integers are 31 bits on 32 bits architectures:
 
<langsyntaxhighlight lang="ocaml">let input_rand_int ic =
let i1 = int_of_char (input_char ic)
and i2 = int_of_char (input_char ic)
Line 345 ⟶ 1,111:
close_in ic;
Printf.printf "%d\n" ri31;
;;</langsyntaxhighlight>
 
but if we really want 32 bits integers there is a module for this:
 
<langsyntaxhighlight lang="ocaml">let input_rand_int32 ic =
let i1 = Int32.of_int (int_of_char (input_char ic))
and i2 = Int32.of_int (int_of_char (input_char ic))
Line 364 ⟶ 1,130:
close_in ic;
Printf.printf "%ld\n" ri32;
;;</langsyntaxhighlight>
 
=={{header|PARI/GP}}==
It works on systems having /dev/urandom and Linux.
 
<syntaxhighlight lang="parigp">rnd(n=10)=extern("cat /dev/urandom|tr -dc '[:digit:]'|fold -w"n"|head -1")</syntaxhighlight>
 
The code above creates a new function rnd() which returns cryptographically strong integers with max. 10 random digits from /dev/urandom. rnd(n) returns integer with max. n random digits. No leading zeros.
{{out}}
<pre>
rnd() = 3055652197
rnd(20) = 75735303746547944580
...
</pre>
 
=={{header|Pascal}}==
This works with FreePascal on "unixoids":
<langsyntaxhighlight lang="pascal">program RandomNumberDevice;
var
byteFile: file of byte;
Line 379 ⟶ 1,158:
writeln('The random byte is: ', randomByte);
end.
</syntaxhighlight>
</lang>
{{out}}
Output:
<pre>
>: ./RandomNumberDevice
Line 389 ⟶ 1,168:
 
=={{header|Perl}}==
Typically one would use a module as they will work on UNIX, Win32, and other O/S's. Crypt::Random::Seed, for instance, will use Win32 sources, EGD/PRNGD, /dev/u?random, or if none of those exist for some reason, a userspace entropy method.
<lang Perl>sub read_random {
<syntaxhighlight lang="perl">use Crypt::Random::Seed;
my $source = Crypt::Random::Seed->new( NonBlocking => 1 ); # Allow non-blocking sources like /dev/urandom
print "$_\n" for $source->random_values(10); # A method returning an array of 32-bit values</syntaxhighlight>
or (similar but many more dependencies):
<syntaxhighlight lang="perl">use Crypt::Random::Source qw/get_weak/; # Alternately get_strong
print unpack('L*',get_weak(4)), "\n" for 1..10;</syntaxhighlight>
 
Or we can read values from /dev/urandom ourselves:
<syntaxhighlight lang="perl">sub read_random {
my $device = '/dev/urandom';
open my $in, "<:raw", $device # :raw because it's not unicode string
Line 398 ⟶ 1,186:
}
 
print "$_\n" for read_random(10);</langsyntaxhighlight>
Whether /dev/urandom is not necessarily good enough for cryptographic work is debated, though on most UNIX systems it is at least as good as the Win32 Crypto API.
=={{header|Perl 6}}==
A lazy list of random numbers:
<lang perl6>my $UR = open("/dev/urandom", :bin) or die "Can't open /dev/urandom: $!";
my @random-spigot := gather loop { take $UR.read(1024).unpack("L*") }
 
=={{header|Phix}}==
.say for @random-spigot[^10];</lang>
My machine does not support the rdrand instruction.<br>
{{out}}
Tested as best I can by commenting out the jnc instructions and replacing rdrand with rdtsc.<br>
<pre>1431009271
I have uploaded replacement pttree.e and pilasm.e (use at your own risk) for
1702240522
anyone wanting to test prior to 0.8.0 being shipped.
670020272
 
588612037
If your chip does not support rdrand, you get {1,0}, else {0,-2147483648..2147483647}.<br>
1864913839
For completeness, I have shown how to convert the signed result to an unsigned one.
2155430433
 
1690056587
<!--<syntaxhighlight lang="phix">(notonline)-->
385405103
<span style="color: #004080;">integer</span> <span style="color: #000000;">res</span> <span style="color: #000080;font-style:italic;">-- 1=failure, 0=success</span>
2366495746
<span style="color: #004080;">atom</span> <span style="color: #000000;">rint</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span> <span style="color: #000080;font-style:italic;">-- random 32-bit int</span>
692037942</pre>
#ilASM{
mov eax,1
cpuid
bt ecx,30
mov edi,1 -- exit code: failure
jnc :exit
-- rdrand sets CF=0 if no random number
-- was available. Intel documentation
-- recommends 10 retries in a tight loop
mov ecx,11
::loop1
sub ecx, 1
jz :exit -- exit code is set already
rdrand eax
-- (the above generates exception #C000001D if not supported)
-- rdtsc
jnc :loop1
lea edi,[rint]
call :%pStoreMint
xor edi,edi
::exit
mov [res],edi
xor ebx,ebx -- important!
}
<span style="color: #0000FF;">?{</span><span style="color: #000000;">res</span><span style="color: #0000FF;">,</span><span style="color: #000000;">rint</span><span style="color: #0000FF;">}</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">res</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span> <span style="color: #008080;">then</span> <span style="color: #000080;font-style:italic;">-- (success)
--
-- To convert a signed 32-bit int to an unsigned one:
--
-- method 1
-- atom urint1 = rint
-- if urint1&lt;0 then urint1+=#100000000 end if</span>
<span style="color: #004080;">atom</span> <span style="color: #000000;">urint1</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">rint</span><span style="color: #0000FF;">+</span><span style="color: #008080;">iff</span><span style="color: #0000FF;">(</span><span style="color: #000000;">rint</span><span style="color: #0000FF;"><</span><span style="color: #000000;">0</span><span style="color: #0000FF;">?</span><span style="color: #000000;">#100000000</span><span style="color: #0000FF;">:</span><span style="color: #000000;">0</span><span style="color: #0000FF;">)</span>
<span style="color: #000080;font-style:italic;">-- method 2</span>
<span style="color: #004080;">atom</span> <span style="color: #000000;">pMem</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">allocate</span><span style="color: #0000FF;">(</span><span style="color: #000000;">4</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">poke4</span><span style="color: #0000FF;">(</span><span style="color: #000000;">pMem</span><span style="color: #0000FF;">,</span><span style="color: #000000;">rint</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">atom</span> <span style="color: #000000;">urint2</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">peek4u</span><span style="color: #0000FF;">(</span><span style="color: #000000;">pMem</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">free</span><span style="color: #0000FF;">(</span><span style="color: #000000;">pMem</span><span style="color: #0000FF;">)</span>
<span style="color: #000080;font-style:italic;">-- method 3</span>
<span style="color: #004080;">atom</span> <span style="color: #000000;">urint3</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">bytes_to_int</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">int_to_bytes</span><span style="color: #0000FF;">(</span><span style="color: #000000;">rint</span><span style="color: #0000FF;">,</span><span style="color: #000000;">4</span><span style="color: #0000FF;">),</span><span style="color: #000000;">signed</span><span style="color: #0000FF;">:=</span><span style="color: #004600;">false</span><span style="color: #0000FF;">)</span>
<span style="color: #0000FF;">?{</span><span style="color: #000000;">urint1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">urint2</span><span style="color: #0000FF;">,</span><span style="color: #000000;">urint3</span><span style="color: #0000FF;">}</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<!--</syntaxhighlight>-->
 
A linux-only solution:
<!--<syntaxhighlight lang="phix">(notonline)-->
<span style="color: #004080;">integer</span> <span style="color: #000000;">fn</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">open</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"/dev/urandom"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"rb"</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">fn</span><span style="color: #0000FF;">=-</span><span style="color: #000000;">1</span> <span style="color: #008080;">then</span>
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"cannot open /dev/urandom\n"</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">else</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{}</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">4</span> <span style="color: #008080;">do</span>
<span style="color: #000000;">s</span> <span style="color: #0000FF;">&=</span> <span style="color: #7060A8;">getc</span><span style="color: #0000FF;">(</span><span style="color: #000000;">fn</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #7060A8;">close</span><span style="color: #0000FF;">(</span><span style="color: #000000;">fn</span><span style="color: #0000FF;">)</span>
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">bytes_to_int</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">,</span><span style="color: #000000;">signed</span><span style="color: #0000FF;">:=</span><span style="color: #004600;">false</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<!--</syntaxhighlight>-->
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">: (in "/dev/urandom" (rd 4))
-> 2917110327</langsyntaxhighlight>
 
=={{header|PowerShell}}==
<syntaxhighlight lang="powershell">
function Get-RandomInteger
{
Param
(
[Parameter(Mandatory=$false,
ValueFromPipeline=$true,
ValueFromPipelineByPropertyName=$true,
Position=0)]
[ValidateScript({$_ -ge 4})]
[int[]]
$InputObject = 64
)
 
Begin
{
$rng = New-Object -TypeName System.Security.Cryptography.RNGCryptoServiceProvider
}
Process
{
foreach($count in $InputObject)
{
$bytes = New-Object -TypeName Byte[] -Argument $count
$rng.GetBytes($bytes)
[System.BitConverter]::ToInt32($bytes,0)
}
}
End
{
Remove-Variable -Name rng -Scope Local
}
}
</syntaxhighlight>
<syntaxhighlight lang="powershell">
4,8,16,32,64,128 | Get-RandomInteger | Format-Wide {$_} -Column 6 -Force
</syntaxhighlight>
{{Out}}
<pre>
1402572656 432337086 413089699 1404567509 -82797202 -261009960
</pre>
As hexadecimal:
<syntaxhighlight lang="powershell">
4,8,16,32,64,128 | Get-RandomInteger | Format-Wide {"0x{0:X}" -f $_} -Column 6 -Force
</syntaxhighlight>
{{Out}}
<pre>
0x24305255 0x916002DD 0x9587046 0x5F236274 0xC0BAF6F0 0xC0B93118
</pre>
 
=={{header|ProDOS}}==
Uses math module:
<syntaxhighlight lang ProDOS="prodos">printline -random- </langsyntaxhighlight>
 
=={{header|PureBasic}}==
PureBasic has the source for the random data is the "/dev/urandom" device on Linux or Mac OSX and the "Microsoft Cryptography API" on Windows.
<langsyntaxhighlight PureBasiclang="purebasic">If OpenCryptRandom()
MyRandom = CryptRandom(#MAXLONG)
CloseCryptRandom()
EndIf</langsyntaxhighlight>
 
=={{header|Python}}==
<langsyntaxhighlight Pythonlang="python">import random
rand = random.randintSystemRandom(1, 10)
rand.randint(1,10)</syntaxhighlight>
</lang>
 
=={{header|Racket}}==
<syntaxhighlight lang="racket">
<lang Racket>
#lang racket
;; Assuming a device to provide random bits:
(call-with-input-file* "/dev/random"
(λ(i) (integer-bytes->integer (read-bytes 4 i) #f)))
</syntaxhighlight>
</lang>
 
=={{header|REXXRaku}}==
(formerly Perl 6)
<lang rexx>/*REXX program generates a random 32-bit number using the RANDOM bif.*/
{{Works with|rakudo|2016-11}}
/*───────── The 32-bit random number is unsigned and constructed from */
/*───────── two smaller 16-bit numbers, and it's expressed in decimal.*/
/*───────── Note: the REXX random bif has a maximum range of 100,000.*/
 
A lazy list of random numbers:
numeric digits 10 /*ensure REXX has enough room. */
_=2**16 /*a handy-dandy constant to have.*/
 
<syntaxhighlight lang="raku" line>use experimental :pack;
say random(0,_-1)*_+random(0,_-1) /*gen an unsigned 32-bit random #*/</lang>
my $UR = open("/dev/urandom", :bin) orelse .die;
'''output'''
my @random-spigot = $UR.read(1024).unpack("L*") ... *;
<pre style="overflow:scroll">
 
.say for @random-spigot[^10];</syntaxhighlight>
{{out}}
<pre>1431009271
1702240522
670020272
588612037
1864913839
2155430433
1690056587
385405103
2366495746
692037942</pre>
 
=={{header|REXX}}==
===version 1===
The &nbsp; 32-bit &nbsp; random number is unsigned and constructed from two smaller 16-bit &nbsp; numbers, &nbsp; and it's expressed in decimal.
 
Note: &nbsp; the REXX &nbsp; '''random''' &nbsp; BIF has a maximum range
of &nbsp; 100,000.
<syntaxhighlight lang="rexx">/*REXX program generates and displays a random 32-bit number using the RANDOM BIF.*/
numeric digits 10 /*ensure REXX has enough decimal digits*/
_=2**16 /*a handy─dandy constant to have around*/
r#= random(0, _-1) * _ + random(0, _-1) /*generate an unsigned 32-bit random #.*/
say r# /*stick a fork in it, we're all done. */</syntaxhighlight>
{{out}}
<pre>
4294967296
</pre>
 
===version 2===
This program generates a random 4 byte character string in the range '00000000'x to 'ffffffff'x
<syntaxhighlight lang="rexx">left=0
rite=0
lo=hex(left)hex(rite)
Say 'low ' c2x(lo)
left=random(0,2**16-1)
rite=random(0,2**16-1)
rand=hex(left)hex(rite)
Say 'random' c2x(rand)
left=2**16-1
rite=2**16-1
hi=hex(left)hex(rite)
Say 'high ' c2x(hi)
Exit
hex: Return d2c(arg(1),2)</syntaxhighlight>
{{out}}
<pre>low 00000000
random 3E4C3CDE
high FFFFFFFF</pre>
 
=={{header|Ring}}==
<syntaxhighlight lang="ring">
nr = 10
for i = 1 to nr
see random(i) + nl
next
</syntaxhighlight>
 
=={{header|RPL}}==
RAND 2 32 ^ * FLOOR
 
=={{header|Ruby}}==
Ruby 1.8.7 introduces the 'securerandom' library. For [[MRI]] users, this library tries to get random numbers by loading OpenSSL, or opening /dev/urandom, or calling CryptGenRandom.
 
<syntaxhighlight lang="ruby">require 'securerandom'
{{works with|Ruby|1.8.7}}
SecureRandom.random_number(1 << 32)
<lang Ruby>require 'securerandom'
 
SecureRandom.random_number(1 << 32)</lang>
#or specifying SecureRandom as the desired RNG:
p (1..10).to_a.sample(3, random: SecureRandom) # =>[1, 4, 5]
</syntaxhighlight>
 
=={{header|Rust}}==
<code>rand</code> used to be part of Rust standard library but it was extracted as a 'crate' (https://crates.io/crates/rand). <code>OsRng</code> uses the appropriate device for many platforms including Unix, Windows, BSD, and iOS (listed [https://docs.rs/rand/0.4/rand/os/struct.OsRng.html here]). Other methods like <code>RDRAND</code> can be found in other crates (https://crates.io/crates/rdrand).
 
<syntaxhighlight lang="rust">extern crate rand;
 
use rand::{OsRng, Rng};
 
fn main() {
// because `OsRng` opens files, it may fail
let mut rng = match OsRng::new() {
Ok(v) => v,
Err(e) => panic!("Failed to obtain OS RNG: {}", e)
};
 
let rand_num: u32 = rng.gen();
println!("{}", rand_num);
}</syntaxhighlight>
 
=={{header|Scala}}==
<syntaxhighlight lang="scala">import java.security.SecureRandom
 
object RandomExample extends App {
new SecureRandom {
val newSeed: Long = this.nextInt().toLong * this.nextInt()
this.setSeed(newSeed) // reseed using the previous 2 random numbers
println(this.nextInt()) // get random 32-bit number and print it
}
}</syntaxhighlight>
 
=={{header|Sidef}}==
<syntaxhighlight lang="ruby">func urandom() {
static device = %f'/dev/urandom'
 
device.open('<:raw', \var fh, \var err) ->
|| die "Can't open `#{device}': #{err}"
 
fh.sysread(\var noise, 4)
'L'.unpack(noise)
}
 
say urandom() # sample: 1989353410</syntaxhighlight>
 
=={{header|Standard ML}}==
{{Works with|Unix}}
<syntaxhighlight lang="sml">fun sysRand32 () =
let
val strm = BinIO.openIn "/dev/urandom"
in
PackWord32Big.subVec (BinIO.inputN (strm, 4), 0) before BinIO.closeIn strm
end
 
val () = print (LargeWord.fmt StringCvt.DEC (sysRand32 ()) ^ "\n")</syntaxhighlight>
 
=={{header|Tcl}}==
<langsyntaxhighlight lang="tcl">package require Tcl 8.5
 
# Allow override of device name
Line 476 ⟶ 1,492:
close $f
return $x
}</langsyntaxhighlight>
Usage:
<langsyntaxhighlight lang="tcl">% puts [systemRandomInteger]
636131349</langsyntaxhighlight>
 
=={{header|UNIX Shell}}==
<syntaxhighlight lang="unix shell">od -An -N 4 -t u4 /dev/urandom</syntaxhighlight>
 
=={{header|Wee Basic}}==
Due to how the code works, any key has to be entered to generate the random number.
<syntaxhighlight lang="wee basic">let keycode=0
let number=1
print 1 "Press any key to generate a random number from 1 to 10.
while keycode=0
let number=number+1
let keycode=key()
rem The maximum number is the number in the "if number=" line with 1 taken away. For example, if this number was 11, the maximum number would be 10. *
if number=11
let number=1
endif
wend
print 1 number
end</syntaxhighlight>
 
=={{header|Wren}}==
<syntaxhighlight lang="wren">import "io" for File
 
File.open("/dev/urandom") { |file|
var b = file.readBytes(4).bytes.toList
var n = b[0] | b[1] << 8 | b[2] << 16 | b[3] << 24
System.print(n)
}</syntaxhighlight>
 
{{out}}
Sample run:
<pre>
2614048905
</pre>
 
=={{header|X86 Assembly}}==
Processors supporting the new RDRAND feature can generate a random 32-bit integer in two instructions:
<syntaxhighlight lang="x86">L: rdrand eax
jnc L</syntaxhighlight>
RDRAND reads the CPU's cryptographically-secure hardware random number generator. The loop is needed because RDRAND can occasionally fail to retrieve a value — it sets the carry flag to indicate whether it succeeded.
 
=={{header|XPL0}}==
Line 488 ⟶ 1,544:
limited to 31 bits.
 
<langsyntaxhighlight XPL0lang="xpl0">code Ran=1;
int R;
R:= Ran($7FFF_FFFF)</langsyntaxhighlight>
 
=={{header|zkl}}==
{{trans|C}}
Linux:
<syntaxhighlight lang="zkl">const RANDOM_PATH="/dev/urandom";
fin,buf:=File(RANDOM_PATH,"r"), fin.read(4);
fin.close(); // GC would also close the file
println(buf.toBigEndian(0,4)); // 4 bytes @ offset 0</syntaxhighlight>
{{out}}
<pre>
2152746403
</pre>
 
{{omit from|GUISS}}
1,151

edits