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.

10 Years
Discussion Span
Last Post by SurviBee
#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() ) ;
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.