mabman mabman - 2 months ago 9x
C Question

C - how to read data from /dev/urandom into a uint64_t variable?

As will probably be painfully obvious, I do not normally program in C. However, after a lot of searching it seems to be the most efficient language to implement what I want to do, namely generate a large number (10 million) of random integers quickly (using an Xorshift* algorithm). The intention is to seed it with /dev/urandom.

I have cobbled together the code below from a variety of sources. It now compiles without warning or error with gcc 5.4.

However, when run, the program is not pulling a random seed from /dev/urandom (or at least it's not populating the value of "seed" correctly). In fact, the value of "seed" seems to always end up the same on my system - 4195584.

In summary, the variation of Xorshift* I cribbed from here requires a uint64_t seed, which I want to pull from /dev/urandom, which is not working currently in my program as it stands.

Environment is Linux (Ubuntu 16.04).

Assistance appreciated.

#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <inttypes.h>

int main (void) {

uint64_t seed;
uint64_t newval;
long int a;

int fd = open("/dev/urandom", O_RDONLY);

printf("%" PRIu64 "\n",seed);

for ( a = 1; a <= 10000000; a = a + 1 ) {
seed ^= seed << 12;
seed ^= seed >> 25;
seed ^= seed << 27;
seed = seed * UINT64_C(2685821657736338717);
newval = abs(seed);
printf("%" PRIu64 "\n",newval);



That is because you need to pass the address of the object to read:

read( fd , &seed , sizeof(seed));