I need to generate a random binary number (or decimal and convert it), and store that number in an array, needless to say im lost and would appreciate any help. Thx

Recommended Answers

All 5 Replies

All numbers are stored in binary. Do you mean generate a random number and then save the binary conversion as a string?

exactly, just need it to be 8 bits long, I've looked around i just cant find anything that doesnt just output it to the screen

The bitset class lets you work with bits, and you can easily print them too.

#include <bitset>
#include <cstdlib>
#include <iostream>

using namespace std;

int main() {
  for ( int i = 0; i < 10; ++i ) {
    cout<< bitset<8>( unsigned char( rand() ) ) <<"\n";
  }

  return 0;
}

There's also a to_string() method that turns the bitset into a string that you can store. But if this is homework I don't know if your teacher will let it slide.

Thanks alot, big help. This isnt for any homework so thanks for the to string tip.

Can u pls help me Can I use the code above for generating many number ...say a million for ex. ?

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.