Generate random long number in C ++

We know that to generate a random long number, we follow these steps in Java

Random r=new Random()
 return r.nextLong();

What will be equivalent to this code in C ++? like this?

return (long) rand();
+5
source share
6 answers

<cstdlib>provides int rand (). You might want to check the man page. If your system is longer than int, you can call rand () twice and put the first value in the upper word.

#include <cstdlib>

long lrand()
{
    if (sizeof(int) < sizeof(long))
        return (static_cast<long>(rand()) << (sizeof(int) * 8)) |
               rand();

    return rand();
}

(it is very unlikely that long is neither the same nor the double size of int, so this is practical, if not theoretically perfect)

rand(). , . srand() . , Windows sizeof (int), .

+12
+9

-, , ++ . , sperate, TR1, , 2003 . ( , ).

, (VS2008 GCC), std:: tr1:: random library; , , std:: random.

, boost : http://www.boost.org/doc/libs/1_44_0/doc/html/boost_random.html

- , ( boost):

boost::mt19937 rng;                 // produces randomness out of thin air
                                    // see pseudo-random number generators
boost::uniform_int<> six(1,6);      // distribution that maps to 1..6
                                    // see random number distributions
boost::variate_generator<boost::mt19937&, boost::uniform_int<> >
         die(rng, six);             // glues randomness with mapping
int x = die();                      // simulate rolling a die
+6
source

Portable hack:

long r = 0;
for (int i = 0; i <sizeof (long) / sizeof (int); i ++)
{
    r = r << (sizeof (int) * CHAR_BITS);
    r | = rand ();
}
return r;

Why do you still need random?

+3
source

This is the method I use. It returns numbers in the range [0, 2 ^ 64-1].

unsigned long long unsignedLongLongRand()
{
    unsigned long long rand1 = abs(rand());
    unsigned long long rand2 = abs(rand());
    rand1 = rand1 << (sizeof(int)*8);   
    unsigned long long randULL = (rand1 | rand2);   
    return randULL;
}
+1
source

this function works like rand () and uses the Unsigned Long Type:

unsigned long _LongRand ()
{

unsigned char MyBytes[4];
unsigned long MyNumber = 0;
unsigned char * ptr = (unsigned char *) &MyNumber;

MyBytes[0] = rand() % 256; //0-255
MyBytes[1] = rand() % 256; //256 - 65535
MyBytes[2] = rand() % 256; //65535 -
MyBytes[3] = rand() % 256; //16777216

memcpy (ptr+0, &MyBytes[0], 1);
memcpy (ptr+1, &MyBytes[1], 1);
memcpy (ptr+2, &MyBytes[2], 1);
memcpy (ptr+3, &MyBytes[3], 1);

return(MyNumber);
}
+1
source

All Articles