doufubian3479 2014-10-10 07:47
浏览 40
已采纳

Go Tour 37中的双倍少运算符

In Go Tour 37 I faced with strange expression 1 << uint(i)

package main

import "fmt"

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

        pow[i] = 1 << uint(i)
    }
    for _, value := range pow {
        fmt.Printf("%d
", value)
    }
}

What do operator << do?

The program got the output:

1
2
4
8
16
32
64
128
256
512

Program exited.
  • 写回答

1条回答 默认 最新

  • doupu1727 2014-10-10 07:55
    关注

    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
    <<
    00000010
    

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

    00000010
    <<
    00000100
    

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

    Conversely, a right shift >> does the opposite, so applying >> to the value 4, produces:

    00000100
    >>
    00000010
    

    ..2.

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

    pow[i] = 512 >> uint(i)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探