Skip to content

Instantly share code, notes, and snippets.

@fp64
Last active January 24, 2023 07:04
Show Gist options
  • Save fp64/b130c7d90b159528671e2265c11c3f7d to your computer and use it in GitHub Desktop.
Save fp64/b130c7d90b159528671e2265c11c3f7d to your computer and use it in GitHub Desktop.
// Public Domain under http://unlicense.org, see link for details.
// Downsized version of u32noise.h ( https://gist.github.com/fp64/126289051f0c9e1b70bcba7c3e07a82f ).
// Probably useless as actual PRNGs, but may be helpful for testing.
#ifndef U16NOISE_H
#define U16NOISE_H
#include <stdint.h>
static inline uint16_t u16noise1(uint32_t n)
{
uint32_t a=n,b=~n;
uint32_t c=0xCF019D85u,d=0x8664F205u;
a^=a>>16;b^=b>>16;
a*=c; b*=d;
a^=a>>16;b^=b>>16;
a*=d; b*=c;
n=a^b;
return (uint16_t)(n^(n>>16));
}
// 16-bit constant: 0xD9F5u.
static inline uint16_t u16noise2(uint32_t n)
{
n^=~n>>16; n*=0xCF019D85u;
n^=~n>>16; n=(n|1u)^(n*n);
return (uint16_t)(n^(n>>16));
}
static inline uint16_t u16noise3(uint32_t n)
{
n^=~n>>19; n=(n|1u)^(n*n);
n^=~n>>19; n=(n|1u)^(n*n);
n^=~n>>19; n=(n|1u)^(n*n);
return (uint16_t)(n^(n>>16));
}
static inline uint16_t u16noise4(uint32_t n)
{
uint16_t a=(uint16_t)(n^(n>>16)),b=(uint16_t)~n,c,d;
c=(uint16_t)(a^(b>>8)) ; d=(uint16_t)(b^(a>>8)) ;
a=(uint16_t)(c*0x4B05u); b=(uint16_t)(d*0xC965u);
c=(uint16_t)(a^(b>>8)) ; d=(uint16_t)(b^(a>>8)) ;
a=(uint16_t)(c*0xE815u); b=(uint16_t)(d*0xF205u);
c=(uint16_t)(a^(b>>8)) ; d=(uint16_t)(b^(a>>8)) ;
a=(uint16_t)(c*0x0675u); b=(uint16_t)(d*0x9D85u);
c=(uint16_t)(a^(b>>8)) ; d=(uint16_t)(b^(a>>8)) ;
return (uint16_t)(c+d);
}
static inline uint16_t u16noise5(uint32_t n)
{
uint16_t a=0x5EEDu,b=(uint16_t)n,c=(uint16_t)(n>>16),d=b,e;
#define ROTL(x,y) ((uint16_t)(((x)<<((y)&15))|((x)>>((-(y))&15))))
e=a-ROTL(b, 9);a=b^ROTL(c, 9);b=c^ROTL(d, 5);c=d+ROTL(e, 5);d=e^ROTL(a, 7);
e=a-ROTL(b,11);a=b^ROTL(c,11);b=c^ROTL(d,11);c=d+ROTL(e, 9);d=e^ROTL(a, 9);
e=a-ROTL(b,13);a=b^ROTL(c, 8);b=c^(d>>5);c=d+(uint16_t)(e<<3);d=e+a;
e=a-ROTL(b, 5);a=b^ROTL(c, 9);b=c^ROTL(d, 7);c=d+ROTL(e, 7);d=e^ROTL(a,11);
e=a-ROTL(b, 7);a=b^ROTL(c, 7);b=c^ROTL(d, 7);c=d+ROTL(e, 7);d=e^ROTL(a,13);
#undef ROTL
return a^c^b^d;
}
static inline uint16_t u16noise6(uint32_t n)
{
n^=~n<<16;
n*=0x8664F205u;
n^= n>>16;
n*=0xAC564B05u;
return (uint16_t)(n^(n>>16));
}
static inline uint16_t u16noise7(uint32_t n)
{
uint16_t a=(uint16_t)n,b=(uint16_t)(n^(n>>16));
a-=(uint16_t)(a<<3); b+=(uint16_t)~(b<<7);
a^=(uint16_t)(a>>9); b^=(uint16_t) (b>>5);
a-=(uint16_t)(a<<5); b+=(uint16_t) (b<<2);
a^=(uint16_t)(a<<2); b^=(uint16_t) (b>>3);
a-=(uint16_t)(a<<2); b+=(uint16_t)~(b<<6);
a^=(uint16_t)(a<<5); b^=(uint16_t) (b>>8);
a^=(uint16_t)(a>>7); b+=(uint16_t)((b<<10)^(b>>6));
return (uint16_t)(a+b);
}
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment