C++ What is contained in the lower 32 bits: Seeding mt

114 views Asked by At

I have a line of code that uses a nano second grab of the high precision clock to seed mersenne twister psudo-random number generator. Something along the lines of this:

rng.seed(duration_cast<nanoseconds>(high_resolution_clock::now().time_since_epoch().count());

I know that mt in boost can only take in 32 bit integers (which is what seed() takes) and that this duration cast to nanoseconds to is at least 64 bits (I also know that this code will cause a conversion warning that can be taken care of with a static_cast).

My question is when this cast to a 32 bit integer what will be the contents of those bits. I know that the lower 32 bits are what the compiler keeps when casting from a 64 bit integer to a 32 bit integer. I am also on a little endian machine. Since I know the current epoch time in seconds is ~1.4*10^9, Will those lower 32 bits be the first ~10 digits of the epoch time or since this is little endian will it be the random gibberish at the end?

Any advice or points to reading are much appreciated.

2

There are 2 answers

4
MSalters On BEST ANSWER

Endianness has nothing to do with it. The "lower" 32 bits of a 64 bits value are bits 0-31, i.e. the bits with values 1<<0 to 1<<31. IOW, taing the lower 32 bits is just taking the value modulo 1<<32.

And yes, for a clock that means taking the rapidly varying part.

0
DarkWanderer On

For safe "downcasting", just use a modulo division:

int64_t nanoseconds = duration_cast<nanoseconds>(high_resolution_clock::now().time_since_epoch().count()
int32_t seed = nanoseconds % std::numeric_limits<int32_t>::max();
rng.seed(seed);