I need to random generate some values in c++. I know that I can use rand() but I need to generate values with the following condition: the generated values must be equal to 2^n (0, 2, 4, 8, ...). Is that possible?

You could populate a vector with the values you deem valid and std::random_shuffle that vector. At that point you could just iterate over the shuffled vector to get random values.

To get a random int between 0 and 31 (inclusive) using rand(), prefer something like int( 32.0 * ( rand() / (RAND_MAX+1.0) ) ) ; Or else, you would be assuming that the least significant 5 bits of the pseudo random number generated by rand() are also randomly distributed.