What is an easy way to generate a random bool in C?

I want to create a random boolean for use in the game, so it should not be cryptographically secure. I will use stdbool.h in my code, and I also made #include <stdlib.h> . Preferably, it should be very fast (since I will generate many of them), and it should be executed in C89 (just preference). I am not at all interested in this in C ++.

Here are some of the ways I came up with:

  • read / dev / urandom, filter out individual digits and> 5 = true, <5 = false.
  • save the rand () call and filter the low / high values.
+4
c random
Oct 11 '15 at 2:13
source share
2 answers

Just call rand() and get the LSB of its return value.

 bool randbool = rand() & 1; 

Remember to call srand() at the beginning.

+9
Oct 11 '15 at 2:15
source share

If you have the RDRAND command RDRAND for the x86_64 processor:

 #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 takes 63 of the 64 generated pseudo-random bits. If you need a higher speed, call _rdseed64_step() once in 64 random bit generators, but change the bit in each generation: val&(1<<0) , val & (1<<1) , val & (1<<2) , val & (1<<3) , ..., val & (1<<i) , ..., val & (1<<63) .

+1
Jul 06 '17 at 9:00
source share



All Articles