Created
February 4, 2013 02:38
-
-
Save Keith-S-Thompson/4704720 to your computer and use it in GitHub Desktop.
Generate random numbers from /dev/urandom
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
#include <limits.h> | |
#define MAX 36 | |
#define URANDOM_DEVICE "/dev/urandom" | |
static FILE *urandom; | |
/* | |
* Returns a random number from 0 to MAX-1 | |
*/ | |
int random_number(void) { | |
int c; | |
do { | |
c = fgetc(urandom); | |
if (c == EOF) { | |
fprintf(stderr, "Failed to read from %s\n", URANDOM_DEVICE); | |
exit(EXIT_FAILURE); | |
} | |
} | |
while (c >= (UCHAR_MAX + 1) / MAX * MAX); | |
return c % MAX; | |
} | |
int main(void) { | |
urandom = fopen(URANDOM_DEVICE, "rb"); | |
if (urandom == NULL) { | |
fprintf(stderr, "Failed to open %s\n", URANDOM_DEVICE); | |
exit(EXIT_FAILURE); | |
} | |
for (int i = 0; i < 10; i ++) { | |
printf("%d\n", random_number()); | |
} | |
fclose(urandom); | |
return 0; | |
} |
Author
Keith-S-Thompson
commented
Feb 4, 2022
via email
Hi, I saw your comment, but I'm not sure what you're saying.
…On Thu, Feb 3, 2022 at 9:24 PM Montaserbdrelden25 ***@***.***> wrote:
***@***.**** commented on this gist.
------------------------------
dev / urandom
—
Reply to this email directly, view it on GitHub
<https://gist.github.com/4704720#gistcomment-4053096>, or unsubscribe
<https://github.com/notifications/unsubscribe-auth/AAFWF4IFNJO5SXO4IBLVKALUZNPHHANCNFSM5NQ22D2A>
.
Triage notifications on the go with GitHub Mobile for iOS
<https://apps.apple.com/app/apple-store/id1477376905?ct=notification-email&mt=8&pt=524675>
or Android
<https://play.google.com/store/apps/details?id=com.github.android&referrer=utm_campaign%3Dnotification-email%26utm_medium%3Demail%26utm_source%3Dgithub>.
You are receiving this because you authored the thread.Message ID:
***@***.***>
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment