r/shittyprogramming • • Jan 09 '23
A far better random number generator
You may have seen u/90Times98Is8820's "terrible random number generator", which relies on undefined behavior. I've written a far better, cryptographically secure random number generator with no compiler warnings that relies on the randomness of cosmic rays.
int generate_bit() {
unsigned long target;
int zero, one, ret;
target = 0;
while (target == 0) ;
while (target == 0) ;
while (target == 0) ;
/* At some point a cosmic ray will flip a bit in target. The loop is
* repeated 3 times in case a cosmic ray breaks out of the loop */
zero = 0;
if (zero != 0) zero = 0;
if (zero != 0) zero = 0;
one = 1;
if (one != 1) one = 1;
if (one != 1) one = 1;
/* The value of any given number in our code may get corrupted, so we
* create standard reference numbers */
ret = zero;
while (target != zero) {
ret ^= one;
target >>= one;
}
/* Set ret to the parity of the position of the flipped bit */
return ret;
}
Hopefully this doesn't become the new iseven.
123
Upvotes
53
u/sojuz151 Jan 09 '23
You need to mark target as volatile, otherwise it will not work. Also if cosmic rays can film multiple bits then you generator will have a bias
3
u/pytness Jan 09 '23
How do you expect the 3 while loops to work if a bit is flipped in target?
1
u/BlockOfDiamond Jan 25 '23
O(infinity)0
u/[deleted] Jan 10 '23
[deleted] — view deleted comment