c++ - C++11 中的随机字节生成

标签 c++ arrays c++11 random function-parameter

我已经编写了一个函数来生成 uint8_t 类型数组中的随机字节,除非我用 random_device 对象为它播种它工作正常但是当我播种时有一些编译器错误。

代码:

#include <algorithm>
#include <random>
#include <functional>
#include <stdint>

void generateInitVector(uint8_t IV_buff[16])
{
    using bytes_randomizer = std::independent_bits_engine<std::default_random_engine, CHAR_BIT, uint8_t>;
    std::random_device rd;
    bytes_randomizer bytes(rd);

    std::generate(std::begin(IV_buff), std::end(IV_buff), std::ref(bytes));
}

编译器错误:

1. error: no matching function for call to 'begin(uint8_t*&)'|

2. error: request for member 'begin' in '__cont', which is of non-class type 'unsigned char*'|

3. error: request for member 'begin' in '__cont', which is of non-class type 'unsigned char* const'|

4. error: no matching function for call to 'end(uint8_t*&)'|

5. error: request for member 'begin' in '__cont', which is of non-class type 'unsigned char*'|

6. error: request for member 'end' in '__cont', which is of non-class type 'unsigned char* const'|

7. error: 'class std::random_device' has no member named 'generate'|

如果我在函数中定义一个 uint8_t 类型的数组

uint8_t data[16];
std::generate(std::begin(data), std::end(data), std::ref(bytes));  //and pass this array in `generate()`.

那么就只剩下错误7了。有什么解决办法吗?

最佳答案

这里的问题是即使你的函数看起来像

void generateInitVector(uint8_t IV_buff[16])

由于数组衰减为指针,它的真正含义是

void generateInitVector(uint8_t * IV_buff)

所以,因为你有一个指针,你不能使用 std::beginstd::end。您需要做的是通过引用传递数组以将其保留为数组。看起来像

void generateInitVector(uint8_t (&IV_buff)[16])

现在您可以使用 std::beginstd::end 并维护数组的大小信息。您甚至可以使用类似

template<std::size_t N>
void generateInitVector(uint8_t (&IV_buff)[N])
{
    using bytes_randomizer = std::independent_bits_engine<std::default_random_engine, CHAR_BIT, uint8_t>;
    std::random_device rd;
    bytes_randomizer bytes(rd);

    std::generate(std::begin(IV_buff), std::end(IV_buff), std::ref(bytes));
}

你也有问题

bytes_randomizer bytes(rd);

std::independent_bits_engine 需要第一个模板参数类型的 PRNG。您使用的 std::default_random_enginestd::random_device 不同。您将需要更改其中一个以匹配另一个以使其编译。例如:

template<std::size_t N>
void generateInitVector(uint8_t (&IV_buff)[N])
{
    using bytes_randomizer = std::independent_bits_engine<std::default_random_engine, CHAR_BIT, uint8_t>;
    std::default_random_engine rd;
    bytes_randomizer bytes(rd);

    std::generate(std::begin(IV_buff), std::end(IV_buff), std::ref(bytes));
}

int main()
{
    uint8_t data[16];
    generateInitVector(data);
}

Compiles just fine

关于c++ - C++11 中的随机字节生成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50623920/

相关文章:

c - 给定一个字符串,编写一个程序通过替换 ? 来生成所有可能的字符串。用 0 和 1?

c - 为什么不能在 C 中返回固定大小/常量数组?

c++ - 使用初始化列表初始化固定数量的变量

c++ - 使用指针打印函数地址

c++ - 从字符串文字初始化 char 数组是否被认为是隐式转换?

c++ - 如何阻止 Scons 在共享库前面添加 lib

c++ - 运算符重载和对象引用

C++ 0x lambda按值捕获总是const?

c++ - 从哪个版本的 C++ 开始允许默认参数?

c++ - 在 c++11 中复制常量大小数组的最简洁方法