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

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

Tour of Go exercise #17: double less operator

问题

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

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

程序的输出结果是:

  1. 1
  2. 2
  3. 4
  4. 8
  5. 16
  6. 32
  7. 64
  8. 128
  9. 256
  10. 512
  11. 程序已退出。
英文:

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

  1. package main
  2. import &quot;fmt&quot;
  3. func main() {
  4. pow := make([]int, 10)
  5. for i := range pow {
  6. pow[i] = 1 &lt;&lt; uint(i)
  7. }
  8. for _, value := range pow {
  9. fmt.Printf(&quot;%d\n&quot;, value)
  10. }
  11. }

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

The program outputs:

  1. 1
  2. 2
  3. 4
  4. 8
  5. 16
  6. 32
  7. 64
  8. 128
  9. 256
  10. 512
  11. Program exited.

答案1

得分: 7

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

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

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

  1. 00000001
  2. <<
  3. 00000010

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

  1. 00000010
  2. <<
  3. 00000100

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

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

  1. 00000100
  2. >>
  3. 00000010

得到数字2。

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

  1. 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:

  1. 00000001
  2. &lt;&lt;
  3. 00000010

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

  1. 00000010
  2. &lt;&lt;
  3. 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:

  1. 00000100
  2. &gt;&gt;
  3. 00000010

..2.

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

  1. 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:

确定