The bitwise &
operator looks at each pair of corresponding bits of its operands, performs an and
using only those two bits, and puts that result in the corresponding bit of the result.
So, if the last bit of UB-LB
is 0, then the last bit of the result is 0
. That is to say, if UB-LB
is even then every output will be even.
The &
is inappropriate to the purpose, unless UB-LB+1
is a power of 2. If you want to find a modulus, then there's no general shortcut: the compiler will already implement %
the fastest way it knows.
Note that I said no general shortcut. For particular values of UB-LB
, known at compile time, there can be faster ways. And if you can somehow arrange for UB
and LB
to have values that the compiler can compute at compile time then it will use them when you write %
.
By the way, using %
does not in fact produce uniformly-distributed integers over the range, unless the size of the range is a power of 2. Otherwise there must be a slight bias in favour of certain values, because the range of your int64()
function cannot be assigned equally across the desired range. It may be that the bias is too small to affect your simulation in particular, but bad random number generators have broken random simulations in the past, and will do so again.
If you want a uniform random number distribution over an arbitrary range, then use std::uniform_int_distribution
from C++11, or the class of the same name in Boost.