Skip to content

Instantly share code, notes, and snippets.

@anzz1
Created September 3, 2025 12:36
Show Gist options
  • Select an option

  • Save anzz1/3d4fdbf2f06729a10785eb270924a46c to your computer and use it in GitHub Desktop.

Select an option

Save anzz1/3d4fdbf2f06729a10785eb270924a46c to your computer and use it in GitHub Desktop.
prng.c
// prng.c
#include <stdint.h>
/* ********************* */
/* * XORSHIFT798 * */
/* * 16-bit * */
/* ********************* */
static uint16_t x798_s = 0;
static inline void x798_init()
{
while (!x798_s) {
x798_s = __rdtsc();
}
}
uint16_t x798_next(void)
{
x798_s ^= x798_s << 7;
x798_s ^= x798_s >> 9;
x798_s ^= x798_s << 8;
return x798_s;
}
/* ********************** */
/* * XOSHIRO128++ * */
/* * 32-bit * */
/* ********************** */
static uint32_t xs128_s[4] = { 0, 0, 0xC4FEB4B3, 0xDEADC0DE };
static inline void xs128_init()
{
if (!xs128_s[0] && !xs128_s[1]) {
uint32_t long tsc = __rdtsc();
xs128_s[0] = ((uint32_t *)&tsc)[0];
xs128_s[1] = ((uint32_t *)&tsc)[1];
}
}
uint32_t xs128_next(void)
{
const uint32_t result = (((xs128_s[0] + xs128_s[3]) << 7) | ((xs128_s[0] + xs128_s[3]) >> (32 - 7))) + xs128_s[0];
const uint32_t t = xs128_s[1] << 9;
xs128_s[2] ^= xs128_s[0];
xs128_s[3] ^= xs128_s[1];
xs128_s[1] ^= xs128_s[2];
xs128_s[0] ^= xs128_s[3];
xs128_s[2] ^= t;
xs128_s[3] = ((xs128_s[3] << 11) | (xs128_s[3] >> (32 - 11)));
return result;
}
/* ********************** */
/* * XOSHIRO256++ * */
/* * 64-bit * */
/* ********************** */
static uint64_t xs256_s[4] = { 0, 0xDEADBEEFC0DEF00D, 0xC4FEB4B3C0FFEEEE, 0xDEADDEADDEADC0DE };
static inline void xs256_init()
{
if (!xs256_s[0]) {
xs256_s[0] = __rdtsc();
}
}
uint64_t xs256_next(void) {
const uint64_t result = (((xs256_s[0] + xs256_s[3]) << 23) | ((xs256_s[0] + xs256_s[3]) >> (64 - 23))) + xs256_s[0];
const uint64_t t = xs256_s[1] << 17;
xs256_s[2] ^= xs256_s[0];
xs256_s[3] ^= xs256_s[1];
xs256_s[1] ^= xs256_s[2];
xs256_s[0] ^= xs256_s[3];
xs256_s[2] ^= t;
xs256_s[3] = ((xs256_s[3] << 45) | (xs256_s[3] >> (64 - 45)));
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment