/* * example of a randoim number generator * the data comes from a random source (hardware) * * Matt Bishop, ECS 36A * -- May 22, 2024 original program * -- May 28, 2024 modified to show *bytes* and add some checking */ #include <stdio.h> #include <sys/random.h> /* * and we're off! */ int main(void) { int i; /* counter in a for loop */ int rv; /* number of random bytes generated */ unsigned int rn; /* holds randomly generated *BITS* */ /* * print the first 20 pseudo-random numbers */ printf(" number byte 1\tbyte 2\tbyte 3\tbyte 4\n"); for(i = 0; i < 20; i++){ /* * generate some random bytes * if there aren't enough random bytes in the source, * just return the number of bytes put in */ rn = 0; if ((rv = getrandom(&rn, sizeof(unsigned int), GRND_NONBLOCK)) == 1){ perror("getrandom"); continue; } /* * print it out as both a hex number and as bytes */ printf("%3d. 0x%08x ", i+1, rn); while(rv-- > 0) printf(" 0x%02x\t", (rn>>(rv*8))&0xff); putchar('\n'); } /* au revoir! */ return(0); }
|
ECS 36A, Programming & Problem Solving Version of April 2, 2024 at 12:13PM
|
You can get the raw source code here. |