Go语言之旅练习#17:双重小于运算符

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

Tour of Go exercise #17: double less operator

问题

在Go Tour的练习#17中,我不理解这个表达式1 << uint(i)的含义。

这个操作符<<是位左移操作符。在这个程序中,它用于计算2的幂。具体来说,1 << uint(i)表示将数字1左移i位,相当于将1乘以2的i次方。

程序的输出结果是:

1
2
4
8
16
32
64
128
256
512

程序已退出。
英文:

In the Go Tour exercise #17, I don't understand this expression 1 &lt;&lt; uint(i)

package main

import &quot;fmt&quot;

func main() {
    pow := make([]int, 10)
    for i := range pow {

        pow[i] = 1 &lt;&lt; uint(i)
    }
    for _, value := range pow {
        fmt.Printf(&quot;%d\n&quot;, value)
    }
}

What is the purpose of this operator ? &lt;&lt;

The program outputs:

1
2
4
8
16
32
64
128
256
512

Program exited.

答案1

得分: 7

这是一个二进制位移运算符,具体来说,它是一个左移运算符(因为它们指向左边)。

它的作用是将一个数字的二进制表示中的所有位向左移动。

例如,数字1的二进制表示是(假设每个字节有8位):00000001。应用左移运算符后得到:

00000001
<<
00000010

这是数字2的二进制表示。再次应用左移运算符得到:

00000010
<<
00000100

这是数字4的二进制表示,依此类推。

相反,右移运算符 >> 则相反操作,所以将值4应用右移运算符后得到:

00000100
>>
00000010

得到数字2。

你可以使用右移运算符将遍历逆序,例如:

pow[i] = 512 >> uint(i)
英文:

Its a binary shift operator. Specifically, its a left shift (since they point to the left).

What it does, is move all bits in the binary representation of a number ... left.

For example. The binary representation of 1 is (with a safe assumption of 8 bits per byte): 00000001. Applying a left shift produces:

00000001
&lt;&lt;
00000010

Which is the binary representation of 2. Applying it again produces:

00000010
&lt;&lt;
00000100

..which is the binary representation of 4.. and so on.

Conversely, a right shift &gt;&gt; does the opposite, so applying &gt;&gt; to the value 4, produces:

00000100
&gt;&gt;
00000010

..2.

You can change the tour to count backwards by using the right shift operator:

pow[i] = 512 &gt;&gt; uint(i)

huangapple
  • 本文由 发表于 2014年10月10日 15:47:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/26294372.html
匿名

发表评论

匿名网友

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

确定