Last active
May 5, 2021 03:47
-
-
Save szaydel/f8bb00e70e259093a5bb6a00a6750a8b to your computer and use it in GitHub Desktop.
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 <stdint.h> | |
#include <string.h> | |
#include <unistd.h> | |
/* | |
PCG code taken from: | |
https://github.com/imneme/pcg-c-basic/blob/bc39cd76ac3d541e618606bcc6e1e5ba5e5e6aa3/pcg_basic.c | |
*/ | |
#define BUFSIZE 1024 * 1024 | |
typedef unsigned char byte; | |
typedef struct { uint64_t state; uint64_t inc; size_t bufsz; byte buf[0]; } pcg32_random_t; | |
void printBits(size_t const size, void const * const ptr) | |
{ | |
unsigned char *b = (unsigned char*) ptr; | |
unsigned char bb; | |
int i, j; | |
for (i = size-1; i >= 0; i--) { | |
// printf("i = %d\n", i); | |
for (j = 7; j >= 0; j--) { | |
bb = (b[i] >> j) & 1; | |
printf("%u", bb); | |
} | |
} | |
puts(""); | |
} | |
size_t pcg32_random_r(pcg32_random_t* rng) | |
{ | |
size_t i; | |
for (i = 0 ; i < rng->bufsz ; i += 4) { | |
uint64_t oldstate = rng->state; | |
// Advance internal state | |
rng->state = oldstate * 6364136223846793005ULL + (rng->inc|1); | |
// Calculate output function (XSH RR), uses old state for max ILP | |
uint32_t xorshifted = ((oldstate >> 18u) ^ oldstate) >> 27u; | |
uint32_t rot = oldstate >> 59u; | |
uint32_t res = (xorshifted >> rot) | (xorshifted << ((-rot) & 31)); | |
//printBits(sizeof(uint32_t), &res); | |
rng->buf[i+3] = res >> 24; | |
rng->buf[i+2] = res >> 16; | |
rng->buf[i+1] = res >> 8; | |
rng->buf[i] = res; | |
} | |
return i; | |
} | |
int main(void) { | |
pcg32_random_t *rng = malloc(sizeof(*rng) + (sizeof(byte) * BUFSIZE)); | |
rng->bufsz = BUFSIZE; | |
rng->state = 12u; | |
rng->inc = 3u; | |
if (isatty(STDOUT_FILENO)) { | |
fprintf(stderr, "You need to redirect to a file!\n"); | |
} | |
pcg32_random_r(rng); | |
ssize_t nwritten = write(STDOUT_FILENO, rng->buf, rng->bufsz); | |
if (nwritten == -1) { | |
perror("write()"); | |
return EXIT_FAILURE; | |
} | |
fprintf(stderr, "Written %zu bytes\n", nwritten); | |
return EXIT_SUCCESS; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment