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
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 −∞.
These are bit shift left and bit shift right operators. They are the same as in the C language and it's derivatives.
x << y
is x times 2 to the power of y
x >> y
is x divided by 2 to the power of y (fractional part discarded)
If you view the numbers as binary, than multiplication by a power of 2 shifts the bits to the left (101 * 2^3 becomes 101000) in the same way as in decimal multiplying by powers of 10 shift the number to the left (12340 * 10^3 becomes 12340000). The converse is true for division by powers of 2. It shifts the binary representation to the right. Hence the name. This is an extremely fast operation for a computer to perform by the way, so it is used a lot in performance critical bit twiddling applications like cryptography for example.
From the specification:
Arithmetic operators ... << left shift integer << unsigned integer >> right shift integer >> unsigned integer
and a bit below:
The shift operators shift the left operand by the shift count specified by the right operand. They implement arithmetic shifts if the left operand is a signed integer and logical shifts if it is an unsigned integer. There is no upper limit on the shift count. Shifts behave as if the left operand is shifted n times by 1 for a shift count of n. As a result, x << 1 is the same as x*2 and x >> 1 is the same as x/2 but truncated towards negative infinity.