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

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

    Distributions take random bits and turn them into numbers. If you actually want random bits then you want to use an engine:

    In particular, those requirements specify the algorithmic interface for types and objects that produce sequences of bits in which each possible bit value is uniformly likely.3

    A single call to a URNG object is allowed to produce and deliver many (typically 32 or more) bits, returning these bits as a single packaged value of an unsigned integer type.4 N3847

    random_device happens to be specified such that accessing uniformly distributed bits is easy:

    std::random_device engine;
    unsigned x = engine(); // sizeof(unsigned) * CHAR_BIT random bits
    

    Note that other engines may not make it quite as easy to get uniformly random bits as random_device, due to returning fewer bits than their result_type can hold or even by effectively returning fractional bits.

    If your concern is that unsigned's size is implementation defined and so random_device returns an implementation defined number of bits, you can write an adapter that either collects enough bits before giving them to you, or one that will give you just enough bits and cache the rest for your next request. (You can also do this to handle other engines which exhibit the previously mentioned issues.)

提交回复
热议问题