12

UDP / TCPを使用してリモートサーバーにパケットを送信するネットワークプログラムをテストしています。そのために、ランダムなバイトストリームを生成したいと思います。

関数は次のとおりです。

unsigned char *gen_rdm_bytestream(int num_bytes)
{
    unsigned char *stream = malloc(num_bytes);
    /*
     * here how to generate?
     */
    return stream;
}
4

4 に答える 4

10

バイトごとに、乱数ジェネレーター関数を呼び出すことができます。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までの疑似乱数が得られます。

于 2013-03-25T18:16:09.690 に答える
2

はい、int rand (void);Cで機能があります。

0からRAND_MAXの範囲の疑似乱数を返します。RAND_MAXは、<cstdlib>で定義されている定数です。

この番号は、呼び出されるたびに明らかに無関係な番号のシーケンスを返すアルゴリズムによって生成されます。このアルゴリズムはシードを使用してシリーズを生成します。シリーズは、関数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

コードパッドリンク

于 2013-03-25T18:13:46.490 に答える
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();
于 2013-03-25T19:08:42.623 に答える
-1

以下は実際のストリーム(std :: istream)であり、C ++11<random>ライブラリを使用します。

これは特に高速であるように書かれていませんが、それは楽しいです:

#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';
}
于 2019-05-08T00:11:30.150 に答える