什么是在C中生成随机bool的简单方法?

时间:2015-10-11 02:13:45

标签: c random

我想生成一个随机布尔值用于游戏,因此它不需要加密安全。我将在代码中使用stdbool.h,我也完成#include <stdlib.h>。优选地,它应该非常快(因为我将生成其中许多),并且它应该能够在C89中完成(只是偏好)。我对C ++中的这一切并不感兴趣。

以下是我提出的一些方法:

  • 从/ dev / urandom中读取,过滤掉单个数字,&gt; 5 = true,&lt; 5 = false。
  • 继续调用rand()并过滤掉低/高值。

2 个答案:

答案 0 :(得分:9)

只需调用background-size: 100%; background-size: 100% auto; /* This is the same as above (included so you can see the similarities below). */ 并获取其返回值的LSB。

background-size: auto 500px; /* If you use percentage (100%), you must set the height of the containing element. */

请务必在开头致电rand()

答案 1 :(得分:1)

如果在x86_64 CPU上设置了RDRAND指令:

#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);
}

但是,这会浪费64个伪随机位中的63个。如果您需要更快的速度,请在64个随机位生成中调用_rdseed64_step()一次,但更改每一代中测试的位:val&(1<<0)val & (1<<1)val & (1<<2),{{1} },...,val & (1<<3),...,val & (1<<i)