Lovenkrands
Lovenkrands

Reputation: 175

Generate random number bigger than 32767

I am trying to assign to a variable a number between 0 and 65535 exactly, but i can't because RAND_MAX is set to 32767. How can I generate a random number bigger than 32767 and at the same time with the possibility that the number generated is between 0 and 65535?

Upvotes: 2

Views: 3384

Answers (2)

Milack27
Milack27

Reputation: 1689

I would try something like this:

int msb = (rand() % 2) << 15;
int random = msb | rand();

That is, I generate two random numbers. The first one (msb) will set the Most Significant Bit of the second (random).

Upvotes: 6

Galik
Galik

Reputation: 48635

If your compiler supports C++11 you can do something like this:

#include <iostream>
#include <random>

int main()
{
    std::random_device rd;
    std::default_random_engine eng {rd()};
    std::uniform_int_distribution<> dist(0, 65535);

    for(unsigned i = 0; i < 10; ++i)
        std::cout << dist(eng) << '\n';
}

Sample output:

38198
49494
41521
10688
1262
51014
36094
16740
1212
59184

Upvotes: 6

Related Questions