I want to generate a random boolean for use in a game, so it does not need to be cryptographically secure. I will use stdbool.h
in my code, and I have also done #include <stdlib.h>
. Preferably, it should be very fast (as I will be generating many of them), and it should be able to be done in C89 (just preference). I am not interested at all in doing this in C++.
Here are some of the ways I've come up with:
Just call rand()
and get the LSB of its return value.
bool randbool = rand() & 1;
Remember to call srand()
at the beginning.
If you have RDRAND
instruction set on a x86_64 CPU:
#include <immintrin.h>
#include <cstdint>
...
bool randBool() {
uint64_t val;
if(!_rdseed64_step(&val)) {
printf("Error generating hardware random value\n");
}
return bool(val&1);
}
However, this wastes 63 out of 64 pseudo-random bits generated. If you need more speed, call _rdseed64_step()
once in 64 random bit generations, but change the bit tested in each generation: val&(1<<0)
, val & (1<<1)
, val & (1<<2)
, val & (1<<3)
, ... , val & (1<<i)
, ..., val & (1<<63)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With