0

In the Go Tour exercise #17, I don't understand this 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 is the purpose of this operator ? <<

The program outputs:

1
2
4
8
16
32
64
128
256
512

Program exited.
Maxim Yefremov
  • 13,671
  • 27
  • 117
  • 166

1 Answers1

7

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)
Simon Whitehead
  • 63,300
  • 9
  • 114
  • 138