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.
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)