英文:
What does the >>= operator do
问题
我正在阅读Go语言中sort函数的实现,其中在func Sort(data Interface)
的实现中有一个特定的循环:
for i := n; i > 0; i >>= 1 {
maxDepth++
}
sort函数的实现:https://golang.org/src/sort/sort.go
有人可以解释一下>>=
运算符是什么意思吗?
编辑: 它只是一个右移操作后再赋值的简写形式。我想可能是它在循环中的使用让我感到困惑。
英文:
I was reading the implementation of sort in go, and there is this particular loop in the implementation of func Sort(data Interface)
:
for i := n; i > 0; i >>= 1 {
maxDepth++
}
Sort implementation : https://golang.org/src/sort/sort.go
Can someone explain to me what does the >>= operator do ?
Edit: It's simply a shift followed by an affectation. I think the fact it was in a loop bugged my mind.
答案1
得分: 5
>>
运算符是右移位运算符。
>>=
是右移位运算符和赋值的缩写形式:
i >>= 1
它等同于:
tmp := i >> 1
i = tmp
而这与以下代码是相同的(无需创建新变量):
i := i >> 1
英文:
The >>
operator is the right shift operator.
>>=
is a contracted form of the right shift operator and assignment:
i >>= 1
It is the same as:
tmp := i >> 1
i = tmp
And that is the same thing as (without the need to create a new variable):
i := i >> 1
答案2
得分: 4
检查:
https://golang.org/ref/spec
左移:整数 << 无符号整数
右移:整数 >> 无符号整数
移位运算符将左操作数按右操作数指定的位数进行移位。如果左操作数是有符号整数,则实现算术移位;如果左操作数是无符号整数,则实现逻辑移位。移位计数没有上限。移位的行为就好像左操作数按照移位计数 n 进行 n 次移位。因此,x << 1 等同于 x*2,x >> 1 等同于 x/2,但结果向负无穷截断。
类似的问题:
https://stackoverflow.com/questions/5801008/go-and-operators
https://stackoverflow.com/questions/26294372/double-less-operator-in-go-tour-37?lq=1
英文:
Check:
https://golang.org/ref/spec
left shift integer << unsigned integer
right shift integer >> unsigned integer
> The shift operators shift the left operand by the shift count
> specified by the right operand. They implement arithmetic shifts if
> the left operand is a signed integer and logical shifts if it is an
> unsigned integer. There is no upper limit on the shift count. Shifts
> behave as if the left operand is shifted n times by 1 for a shift
> count of n. As a result, x << 1 is the same as x*2 and x >> 1 is the
> same as x/2 but truncated towards negative infinity.
Similar questions:
https://stackoverflow.com/questions/5801008/go-and-operators
https://stackoverflow.com/questions/26294372/double-less-operator-in-go-tour-37?lq=1
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论