I wrote this earlier today. Compiles in C and C ++ using the GNU compiler on Linux.
#include "rands.h" #include <sys/types.h> /* for open(2) */ #include <sys/stat.h> /* for open(2) */ #include <fcntl.h> /* for open(2) */ #include <unistd.h> /* for read(2), close(2) */ #define DEVURANDOM "/dev/urandom" typedef uint8_t TYPE; TYPE getRandU8() { TYPE rnum = 0; int fd = open(DEVURANDOM, O_RDONLY); if (fd != -1) { (void) read(fd, (void *)&rnum, sizeof(TYPE)); (void) close(fd); } return rnum; }
You can change the TYPE to int8_t, uint16_t, int16_t, uint32_t, int32_t, uint64_t and int64_t if necessary (and change the function name accordingly). You can also use (signed / unsigned) char, short, int, long, long long, etc. The rands.h file (in the same directory) just has function prototypes for binding.
source share