Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's a simple way to generate a random bool in C? [duplicate]

Tags:

c

random

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:

  • read from /dev/urandom, filter out single digits and >5 = true, <5 = false.
  • keep calling rand() and filter out low/high values.
like image 748
sadljkfhalskdjfh Avatar asked Oct 11 '15 02:10

sadljkfhalskdjfh


2 Answers

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

bool randbool = rand() & 1;

Remember to call srand() at the beginning.

like image 137
timrau Avatar answered Nov 03 '22 20:11

timrau


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) .

like image 27
Serge Rogatch Avatar answered Nov 03 '22 20:11

Serge Rogatch