Pseudo random number generator
I tried making a PRNG and here is what I came up with.
(With a small testing main for your convenience ;)
#include <stdio.h>
#include <limits.h>
/*
Get a specified bit and shift it to the specified position
*/
#define GET_BIT(i, what_bit, pos) \
((!!((i) & (1 << ((what_bit) - 1)))) << ((pos) - 1))
unsigned int my_random(void)
{
static unsigned int i1 = 0x9abcdef0,
i2 = 0x12345678;
unsigned int hibit;
/*roll to the left*/
hibit = !!(i1 & (1 << (sizeof(unsigned int) * CHAR_BIT - 1)));
i1 <<= 1;
i1 |= hibit;
/* xor two arbitrary bits together */
i1 ^= GET_BIT(i1, 14, 5);
/*roll to the left*/
hibit = !!(i2 & (1 << (sizeof(unsigned int) * CHAR_BIT - 1)));
i2 <<= 1;
i2 |= hibit;
/* xor two arbitrary bits together */
i2 ^= GET_BIT(i2, 13, 2);
return i2 ^ i1;
Quote:
}
int main(void)
{
int i;
for(i = 0;i < 200;i++)
printf("%u\n", my_random() % 0x10u);
putchar('\n');
for(i = 0;i < 200;i++)
printf("%u\n", my_random());
return 0;
Quote:
}
What do you think? I know not everything is optimal and everything,
but is this simple generator any good? Tweaking the different
"magic" numbers and the start numbers have an effect. The same goes
for the operator used in the return statement (Allthough less
important).
--
Thomas Stegen
http://www.*-*-*.com/