I'm writing a simple program that would assign each letter and several symbols to a randomly generated 8bit binary pattern. I want to take a rand() #, convert it to a 1 byte binary number, and store that number as a string in one row of a two dimensional array/vector.

I need to create alot of these numbers and fast, what is the most efficient way to do this?
Any help greatly appreciated, thanks.

Recommended Answers

All 2 Replies

#include <iostream>
#include <bitset>
#include <vector>
#include <string>
//#include <random> // c++0x
#include <boost/random.hpp> // c++98 + boost
using namespace boost ; // c++98 + boost
using namespace std ;

void fill_row_with_random_bit_pattern( vector<string>& row, size_t N )
{
  enum { NBITS = 8 } ;
  row.clear() ; row.reserve(N) ;
  static mt19937 engine ; // mersene twister; fast with acceptable quality.
  // see http://en.wikipedia.org/wiki/Mersenne_twister
  static uniform_int<> distrib( 0, (1U<<NBITS) - 1 ) ; // uniform over NBITS
  static variate_generator< mt19937&, uniform_int<> >
                                     generator( engine, distrib ) ; // rng 
  for( size_t i=0 ; i<N ; ++i )
    row.push_back( bitset<NBITS>( generator() ).to_string() ) ;
}

Wow, thank you, you rock

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.