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

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

    To answer your question: You can't.

    The standard does not allow std::uniform_int_distribution to be templated on char, signed char, or unsigned char. Some believe that this is a defect in the standard, but it is the case.

    You can simply template std::uniform_int_distribution on unsigned short, and set its min/max range to std::numeric_limits::min() and std::numeric_limits::max(), and then simply assign the result to an unsigned char.

    From the standard:

    Throughout this subclause 26.5, the effect of instantiating a template:

    [...]

    e) that has a template type parameter named IntType is undefined unless the corresponding template argument is cv-unqualified and is one of short, int, long, long long, unsigned short, unsigned int, unsigned long, or unsigned long long.

    §26.5.1.1 [rand.req.genl]

    Moreover:

    You should use std::mt19937 to actually generate your random bytes. std::random_device is liable to be slow, and likely produces entropy with statistical properties (i.e. suitability for use in cryptography) that you don't need.

    That said, you will need to seed your std::mt19937. You can do this with a std::random_device and a std::seed_seq.

    Note that if you don't use a std::seed_seq to seed your std::mt19937, your std::mt19937 will be left with many, many zeroes in its internal state, and it will therefore take it quite a while to "warm up".

    For more information on "warm up", see here.

提交回复
热议问题