两个表达式之间的单个和号

huangapple go评论84阅读模式
英文:

single ampersand between 2 expressions

问题

我正在查看Go语言源代码中的模块math/rand。我在那里找到了一行有趣的代码:

if n&(n-1) == 0 { // n是2的幂,可以进行位掩码

我只是好奇,n&(n-1)是什么意思?

我可以理解n && (n-1)。它是两个布尔表达式之间的“与”运算符。我可以理解&n。它是n变量的地址。但是n&(n-1)是什么意思,我无法理解。

完整的方法代码:

// Int63n以int64的形式返回[0,n)范围内的非负伪随机数。
// 如果n <= 0,则会引发panic。
func (r *Rand) Int63n(n int64) int64 {
    if n <= 0 {
        panic("invalid argument to Int63n")
    }
    if n&(n-1) == 0 { // n是2的幂,可以进行位掩码
        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
}
英文:

I was looking at the Go language source code, module math/rand. I found there one interesting line

if n&amp;(n-1) == 0 { // n is power of two, can mask

I'm just curious, what does n&amp;(n-1) mean?

I would understand n &amp;&amp; (n-1). It would be AND operator between 2 boolean expressions. I would understand &amp;n. It's address of n variable. But what is n&amp;(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 &lt;= 0.
func (r *Rand) Int63n(n int64) int64 {
	if n &lt;= 0 {
		panic(&quot;invalid argument to Int63n&quot;)
	}
	if n&amp;(n-1) == 0 { // n is power of two, can mask
		return r.Int63() &amp; (n - 1)
	}
	max := int64((1 &lt;&lt; 63) - 1 - (1&lt;&lt;63)%uint64(n))
	v := r.Int63()
	for v &gt; max {
		v = r.Int63()
	}
	return v % n
}

答案1

得分: 9

这是按位与运算符。

// 输出2,因为3 (0x0011) & 2 (0x0010) = 2 (0x0010)
fmt.Println(3 & 2)

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

英文:

This is the bitwise AND operator.

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

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

huangapple
  • 本文由 发表于 2015年6月9日 21:28:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/30733455.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定