Hi,

I am trying to generate 2000 random 3 bit binary numbers. I am using the following code to do that but I am getting an error.

#include <bitset>
#include <stdio.h>
#include <cstdlib>
#include <strings.h>
#include <iostream>
#include <vector>
#include <time.h>

using namespace std;

int main()
{

for(int i=0; i<2000; i++)
{
cout<< bitset<3> (unsigned char ( (rand() ) ) <<"\n";
}
return 0;
}

Can someone tell me the right way to generate random binary numbers like

000
001
010
..

Thanks

Its very simple to do. All you need is one function that converts an integer to a 3 bit binary number. If fact, its so simple I will give it to you :)

#include <iostream>
#include <ctime>

using namespace std;

void toBin(int num, char *lpStr, int len) {
	lpStr[len] = 0;
	for (int i = len - 1, remainder; i >= 0; i--)
		lpStr[i] = '0' + (remainder = num % 2, num /= 2, remainder);
}

int main() {
	char bin[4];
	srand(time(NULL));
	for (int i = 0; i < 2000; ++i) {
		toBin(rand()%7, bin, 3);
		cout << bin << '\n';
	}
	cin.ignore();
    return 0;
}

Heres how to get the binary of an integer which is what the function toBin does.
Say you want the binary of 18.

18 % 2 = 0
9  % 2 = 1
4  % 2 = 0
2  % 2 = 0
1  % 2 = 1

bin = 10010

. . .
int main()
{
for(int i=0; i<2000; i++)
{
cout<< bitset<3> (unsigned char ( (rand() ) ) <<"\n";
}
return 0;
}
. . .

Hello,

your idea of using <bitset> is completely correct. You only need to make some improvements like in:

int main(){
  const int n=3, d=1<<n;
  for (int i=0;i<2000;i++)cout<<bitset<n>(rand()%d)<<endl;
  return 0;
}
/* Result
001
011
001
011
011
110
011
100
111
...
*/

Isn't this a whole lot simpler than that queer one, eh? :D

krs,
tesu

This article has been dead for over six months. Start a new discussion instead.