Random number generator (device): Difference between revisions
Content added Content deleted
(Added Mathematica) |
(→{{header|C}}: The first example now makes fewer assumptions about the host environment (a uint32_t isn't required for this code to work). Additionally, this code compiles as C89 and returns EXIT_FAILURE instead of 1.) |
||
Line 27: | Line 27: | ||
It works on systems having /dev/urandom, like [[GNU]]/[[Linux]]. |
It works on systems having /dev/urandom, like [[GNU]]/[[Linux]]. |
||
<lang c>#include < |
<lang c>#include <stdio.h> |
||
#include < |
#include <stdlib.h> |
||
#include <stdint.h> |
|||
#define RANDOM_PATH "/dev/urandom" |
|||
int main(int argc, char **argv) |
|||
⚫ | |||
uint32_t v; |
|||
FILE *r = fopen("/dev/urandom", "r"); |
|||
if (r == NULL) |
|||
⚫ | |||
perror("/dev/urandom"); |
|||
⚫ | |||
⚫ | |||
int main(void) |
|||
size_t br = fread(&v, sizeof v, 1, r); |
|||
⚫ | |||
if (br < 1) |
|||
unsigned char buf[4]; |
|||
{ |
|||
unsigned long v; |
|||
fputs("/dev/urandom: Not enough bytes\n", stderr); |
|||
FILE *fin; |
|||
return 1; |
|||
} |
|||
if ((fin = fopen(RANDOM_PATH, "r")) == NULL) { |
|||
⚫ | |||
fprintf(stderr, "%s: unable to open file\n", RANDOM_PATH); |
|||
⚫ | |||
return |
return EXIT_FAILURE; |
||
⚫ | |||
if (fread(buf, 1, sizeof buf, fin) != sizeof buf) { |
|||
fprintf(stderr, "%s: not enough bytes (expected %u)\n", |
|||
RANDOM_PATH, (unsigned) sizeof buf); |
|||
return EXIT_FAILURE; |
|||
⚫ | |||
⚫ | |||
v = buf[0] | buf[1] << 8UL | buf[2] << 16UL | buf[3] << 24UL; |
|||
⚫ | |||
⚫ | |||
}</lang> |
}</lang> |
||