Efficiently generating random bytes of data in C++11/14

前端 未结 4 1147
终归单人心
终归单人心 2021-02-12 23:23

My requirement is to generate random bytes of data (not random numbers) aka uniformly distributed bits.

As such I was wondering what are the correct/efficient w

4条回答
  •  被撕碎了的回忆
    2021-02-13 00:23

    I think the key to efficiency is to get the maximum number of values from every random number that is generated. Here's a small tweak to your original code that does that.

    #include 
    #include 
    #include 
    
    int main()
    {
       std::random_device rd;
       std::uniform_int_distribution dist(0,0xFFFFFFFFu);
       std::vector data(1000);
       int offset = 0;
       uint32_t bits = 0;
       for (char& d : data)
       {
          if (offset == 0)
             bits = dist(rd);
          d = static_cast(bits & 0xFF);
          bits >>= 8;
          if (++offset >= 4)
             offset = 0;
       }
       return 0;
    }
    

    If getting 4 bytes from every 32 bits doesn't work, try 3 bytes from 24 bits.

提交回复
热议问题