在C ++ 11/14中高效地生成数据的随机字节 [英] Efficiently generating random bytes of data in C++11/14

查看:148
本文介绍了在C ++ 11/14中高效地生成数据的随机字节的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的要求是生成随机字节的数据(不是随机数),也就是均匀分布的位。

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

我想知道是什么是使用C ++ 11/14随机工具执行此操作的正确/有效方法。我看过这些示例,但它们 all 似乎专注于数字生成(整数,浮点数等)

As such I was wondering what are the correct/efficient ways of doing this using C++11/14 random facilities. I've had a look around at the examples, but they all seem to focus on number generation (ints, floats etc)

我正在使用的当前解决方案如下:

Current solution I'm using is the following:

#include <vector>
#include <random>

int main()
{
   std::random_device rd;
   std::uniform_int_distribution<int> dist(0,255);
   std::vector<char> data(1000);
   for (char& d : data)
   {
      d = static_cast<char>(dist(rd) & 0xFF);
   }
   return 0;
}


推荐答案

分布采用随机位并转向他们成数字。如果您实际上想要随机位,那么您想使用引擎:

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


特别是,这些要求指定了产生位序列的类型和对象的算法接口。 3

对URNG对象的单个调用被允许产生并传递许多(通常为32个或更多)位,将这些位作为无符号整数类型的单个打包值返回。 4
N3847

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 恰好被指定为易于访问均匀分布的位:

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

请注意,其他引擎可能不太容易获得统一的随机性由于返回的位数少于它们的result_type所能容纳的位数,或者甚至有效地返回了小数位数,因此这些位数称为 random_device

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.

如果您担心的是 unsigned 的大小是实现定义的,因此 random_device 返回实现定义的位数,您可以编写一个适配器要么收集足够的位然后再提供给您,要么收集足够的位并为下一个请求缓存其余位。 (您也可以执行此操作以处理出现前面提到的问题的其他引擎。)

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.)

这篇关于在C ++ 11/14中高效地生成数据的随机字节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆