-3

Hi. Is there any way to set the size of random numbers?( in random number generator "rand()")

For example I want to generate 10 digits random numbers.

and one more question, how can i set random function to generate numbers between 0 and 1 (for example 0100110110) ?

Z chen
  • 11
  • 3
  • You can apply a bitmask to the generated number like `myRand = myRand & 0x3ff;` to ensure it contains only 10 significant bits. – πάντα ῥεῖ Feb 04 '15 at 12:13
  • In short, no. Do you mean no leading 0s in your "10 digit" numbers? Do you know how to get a random number in a range? – doctorlove Feb 04 '15 at 12:19
  • @πάνταῥεῖ As is guess 0x3FF is the number 1111111111 in binary. is it right ? can you explain what does it do exactly ? – Z chen Feb 04 '15 at 12:22
  • @doctorlove I mean that i only want the random number be in binary form (0 or 1) – Z chen Feb 04 '15 at 12:24
  • @Zchen A decimal number with only ones and zeroes is still decimal, not binary. – molbdnilo Feb 04 '15 at 12:25
  • @molbdnilo thanks. Do you know how can i limit rand() function to generate only 0 or 1 ? – Z chen Feb 04 '15 at 12:30
  • @Zchen _"can you explain what does it do exactly ?"_ Using the binary `&` (and) operation it will restrict a number to have more than 10 significant bits. – πάντα ῥεῖ Feb 04 '15 at 12:41
  • @πάνταῥεῖ thanks. Is there any other bitmask to restrict a number more than 10 significant bits ? – Z chen Feb 04 '15 at 13:19

1 Answers1

-1

Im not sure about setting the size of the numbers. However I dont think it would be possible to get each digit to produce just a 0 or 1.

What you can do however is something like below:

          ostringstream 10digitNumber;
          for(int i = 0 ; i < 10 ; i ++){

                v1 = rand() % 2;// generate o or 1
                10digitNumber<< v1;// build up a string of 1 and 0

           }
         int real10DigitNumber = static_cast<int>10digitNumber);              //                      typecast to integer

Please forgive me if my syntax isn't 100 %. Its being awhile since I used c++.

Vann
  • 29
  • 5
  • You should avoid `%` - http://channel9.msdn.com/Events/GoingNative/2013/rand-Considered-Harmful – doctorlove Feb 04 '15 at 12:28
  • Thanks Z chen, let me know if you have any difficulty. Please correct syntax I can already see Im missing a bracket. – Vann Feb 04 '15 at 12:45