我正在测试一个使用UDP / TCP将数据包发送到远程服务器的网络程序,为此, 我想生成一些随机字节流。
这是功能:
unsigned char *gen_rdm_bytestream(int num_bytes)
{
unsigned char *stream = malloc(num_bytes);
/*
* here how to generate?
*/
return stream;
}
答案 0 :(得分:6)
对于每个字节,您可以调用随机数生成器函数。 C标准提供函数rand
。在使用它之前,您应该通过调用srand
来初始化随机序列。
gen_rdm_bytestream
可能看起来像这样:
#include <stdlib.h>
#include <time.h>
unsigned char *gen_rdm_bytestream (size_t num_bytes)
{
unsigned char *stream = malloc (num_bytes);
size_t i;
for (i = 0; i < num_bytes; i++)
{
stream[i] = rand ();
}
return stream;
}
srand ((unsigned int) time (NULL));
由于stream
是无符号的,如果rand
返回的值大于UCHAR_MAX
,则会减少(模UCHAR_MAX
}。因此,您将获得0到255之间的伪随机数。
答案 1 :(得分:1)
是的,您在C中有int rand (void);
个功能,
返回0到RAND_MAX范围内的伪随机整数。 RAND_MAX是在。中定义的常量。
此数字由算法生成,该算法每次调用时都会返回一系列明显不相关的数字。该算法使用种子生成序列,应使用函数srand().将其初始化为某个独特的值
编辑:
在您发表评论时,我为您编写了一段代码,可以帮助您演示,如何使用rand(),该程序及其输出是:
#include <stdio.h>
#include <stdlib.h> /* srand, rand */
#include <time.h>
int main (){
int i=0;
srand (time(NULL));
printf("Five rand numbers: \n");
for(i = 1; i <= 5; i++){
printf("\n %d", rand());
}
printf("Five rand numbersb between 2 to 5: \n");
for(i = 1; i <= 5; i++){
printf("\n %d", (2 + rand()%4));
}
return 1;
}
输出:
Five rand numbers:
1482376850
1746468296
1429725746
595545676
1544987577
Five rand numbers, between 2 to 5:
2
5
3
4
3
答案 2 :(得分:1)
这是在给定范围内生成随机整数值的一般函数:
#include <stdlib>
/**
* Assumes srand has already been called
*/
int randInRange( int min, int max )
{
double scale = 1.0 / (RAND_MAX + 1);
double range = max - min + 1;
return min + (int) ( rand() * scale * range );
}
利用此功能创建未签名的char
值:
u_char randomByte()
{
return (u_char) randInRange( 0, 255 );
}
所以,
for ( i = 0; i < numBytes; i++ )
stream[i] = randomByte();
答案 3 :(得分:0)
以下是实际的流(std :: istream),并使用C ++ 11
这不是特别写得很快,但这很有趣:
#include <iostream>
#include <string>
#include <array>
#include <algorithm>
#include <random>
class RandomBuf : public std::streambuf
{
private:
size_t m_size;
std::array<char, 64> m_buf;
std::mt19937_64 m_twister;
std::uniform_int_distribution<char> m_dist;
protected:
int_type underflow() override {
if (m_size == 0)
return EOF;
size_t size = std::min(m_size, m_buf.size());
setg(&m_buf[0], &m_buf[0], &m_buf[size]);
for (size_t i = 0; i < size; ++i)
m_buf[i] = m_dist(m_twister);
m_size -= size;
return 0;
}
public:
RandomBuf(size_t size, char b, char e) : m_size(size), m_dist(b, e) { }
};
class Random : public std::istream
{
private:
RandomBuf m_streambuf;
public:
Random(size_t size, char b, char e) : m_streambuf(size, b, e) {
rdbuf(&m_streambuf);
}
};
// Example usage:
int main()
{
Random random(100, 'a', 'z'); // Create an istream that produces 100 pseudo-random characters in the interval ['a', 'z'].
// Read random stream to a string:
std::string str;
random >> str;
// Print result.
std::cout << str << std::endl;
}
该程序的输出(正是因为该标准保证默认构造的梅森捻线机具有给定的种子):
ugsyakganihodonwmktggixegfszuclgupylingbnscxadzqhjmhhyqtssbmctlpchqfflzfwhvjywmajtnkaxczrmtpnlvwmzxd
编辑:
为了获得额外的奖励积分,我添加了StreamHasher类: https://wandbox.org/permlink/bIDCVTnJjkdafARo
只需添加类:
class StreamHasherBuf : public std::streambuf
{
private:
size_t m_hash;
std::array<char, 64> m_buf; // The resulting hash value is a function of the size of the array!
static constexpr size_t bufsize = std::tuple_size_v<decltype(m_buf)>;
void add_and_reset_put_area()
{
boost::hash_combine(m_hash, boost::hash_range(pbase(), pptr()));
setp(&m_buf[0], &m_buf[bufsize]);
}
protected:
int_type overflow(int_type c) override
{
if (c != EOF)
{
if (pptr() == epptr())
add_and_reset_put_area();
*pptr() = c;
pbump(1);
}
return 0;
}
public:
StreamHasherBuf() : m_hash(0) { setp(&m_buf[0], &m_buf[bufsize]); }
size_t hash()
{
add_and_reset_put_area();
return m_hash;
}
};
class StreamHasher : public std::ostream
{
private:
StreamHasherBuf m_streambuf;
public:
StreamHasher() { rdbuf(&m_streambuf); }
size_t hash() { return m_streambuf.hash(); }
};
例如
int main()
{
RandomBuf random(100, 'a', 'z'); // Create a streambuf that produces 100 pseudo-random characters in the interval ['a', 'z'].
StreamHasher hasher;
hasher << &random;
std::cout << hasher.hash() << '\n';
}