0

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

3
Contributors
5
Replies
6
Views
10 Years
Discussion Span
Last Post by samtronxindia
0

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

0

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

0

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.

0

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

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.