I’m looking for information on Google’s Go language. In “A Tour of Go” they have this code:
const (
Big = 1<<100
Small = Big>>99
)
But what do <<
and >>
mean?
You can see all of the code at http://tour.golang.org/#14
They are bitwise shift operators. x << y
means x × 2y, while x >> y
means x × 2−y or, equivalently, x ÷ 2y. These operators are generally used to manipulate the binary representation of a value, where, just like with a power of 10 in decimal, multiplying or dividing by a power of two has the effect of “shifting” the digits left or right, respectively:
// Left shift:
13 * 2 == 26 // decimal
1101 * 10 == 11010 // binary (13 is 8 + 4 + 0 + 1)
// Right shift (brackets denote discarded portion):
13 / 2 == 6[.5] // decimal
1101 / 10 == 110[.1] // binary
Because you are operating on integers and a right shift typically results in fractional values, there are a couple of ways to handle how the result of a right shift is rounded. In Go, right shift is a logical shift on unsigned values and an arithmetic shift on signed values. Logical shift always rounds toward zero, while arithmetic shift always rounds down, that is, toward −∞.