I was looking at the Go language source code, module math/rand. I found there one interesting line
if n&(n-1) == 0 { // n is power of two, can mask
I'm just curious, what does n&(n-1)
mean?
I would understand n && (n-1)
. It would be AND
operator between 2 boolean expressions. I would understand &n
. It's address of n
variable. But what is n&(n-1)
I cannot figure out.
Full method code:
// Int63n returns, as an int64, a non-negative pseudo-random number in [0,n).
// It panics if n <= 0.
func (r *Rand) Int63n(n int64) int64 {
if n <= 0 {
panic("invalid argument to Int63n")
}
if n&(n-1) == 0 { // n is power of two, can mask
return r.Int63() & (n - 1)
}
max := int64((1 << 63) - 1 - (1<<63)%uint64(n))
v := r.Int63()
for v > max {
v = r.Int63()
}
return v % n
}
This is the bitwise AND operator.
http://play.golang.org/p/JFto4ZHUEC