single ampersand between 2 expressions

2.6k views Asked by At

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
}
1

There are 1 answers

0
Ainar-G On BEST ANSWER

This is the bitwise AND operator.

// Prints 2, because 3 (0x0011) & 2 (0x0010) = 2 (0x0010)
fmt.Println(3 & 2)

http://play.golang.org/p/JFto4ZHUEC