Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <inttypes.h>
- inline uint64_t swap64( uint64_t n, _Bool high ) {
- if( high ) {
- return ( ( n >> 16 ) & 0x0000FFFF00000000 ) |
- ( ( n << 16 ) & 0xFFFF000000000000 ) |
- ( n & 0x00000000FFFFFFFF );
- } else {
- return ( ( n >> 16 ) & 0x000000000000FFFF ) |
- ( ( n << 16 ) & 0x00000000FFFF0000 ) |
- ( n & 0xFFFFFFFF00000000 );
- }
- }
- // RNG state
- uint64_t rnd;
- uint32_t long_rnd( void ) {
- register uint64_t a, b;
- // D0+D1, D2+D3
- a = ( rnd & 0xFFFFFFFFFFFFFF0E ) | 0x20;
- b = a;
- b *= 2;
- a += b;
- b = swap64( b, 1 );
- b = swap64( b, 0 );
- b = ( b & 0xFFFF0000FFFF0000 ) | ( ( b & 0xFFFF ) << 32 );
- a += b;
- rnd = a;
- return (uint32_t)( a >> 32 );
- }
- uint32_t random_seed( uint64_t seed ) {
- seed += ( seed << 32 );
- rnd = seed;
- return long_rnd();
- }
- uint32_t random_seed_crazybus( uint32_t seed ) {
- uint32_t garbage; // uninitialized
- garbage += seed;
- rnd = garbage; rnd <<= 32; rnd |= seed;
- return long_rnd();
- }
- uint16_t gen_random( uint16_t range ) {
- if( range > 0 )
- range = ( long_rnd() >> 16 ) % range;
- return range;
- }
- // testing
- int main( void ) {
- int i;
- printf( "%016"PRIX64"\n", rnd );
- random_seed( 1 );
- printf( "%016"PRIX64"\n", rnd );
- for( i = 0; i < 16; ++i )
- printf( "%u\n", gen_random( 65535 ) );
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement