在Go Tour 37中减少两倍的操作员 [英] double less operator in Go Tour 37

查看:107
本文介绍了在Go Tour 37中减少两倍的操作员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Go Tour 37 中,我遇到了奇怪的表情 1<<<<<< ; uint(i)

 包主
$ b $导入fmt

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

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

运算符 <?lt; / code>做什么?

程序得到了输出:

  1 
2
4
8
16
32
64
128
256
512

程序已退出。


解决方案

具体来说,它是一个左移(因为它们指向左边)。



它的作用是将数字的二进制表示中的所有位移到左边。



例如。 1的二进制表示是(每个字节有8位安全假设): 00000001 。应用左移产生:

  00000001 
<<
00000010

这是二进制表示2.再次应用会产生:

  00000010 
<<
00000100

..这是4 ..等的二进制表示。



相反,右移>> 则相反,所以应用> < / code>到值4,产生:

  00000100 
>>
00000010



<2>




  pow [i] = 512>您可以改变游程以使用右移运算符向后计数: > uint(i)


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\n", value)
    }
}

What do operator << do?

The program got the output:

1
2
4
8
16
32
64
128
256
512

Program exited.

解决方案

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)

这篇关于在Go Tour 37中减少两倍的操作员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆