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

前端 未结 4 1145
终归单人心
终归单人心 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:30

    What you're looking for is the std::independent_bits_engine adaptor:

    #include 
    #include 
    #include 
    #include 
    #include 
    
    using random_bytes_engine = std::independent_bits_engine<
        std::default_random_engine, CHAR_BIT, unsigned char>;
    
    int main()
    {
        random_bytes_engine rbe;
        std::vector data(1000);
        std::generate(begin(data), end(data), std::ref(rbe));
    }
    

    Note that the accepted answer is not strictly correct in a general case – random engines produce unsigned values belonging to a range [min(), max()], which doesn't necessarily cover all possible values of the result type (for instance, std::minstd_rand0::min() == 1) and thus you may get random bytes that are not uniformly distributed if using an engine directly. However, for std::random_device the range is [std::numeric_limits::min(), std::numeric_limits::max()], so this particular engine would also work well without the adaptor.

提交回复
热议问题