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
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
<<
and>>
are shift operators.They work on the underlying binary representation of a number, and 'shift' the number left of the operator left or right by the amount of bits specified on the right of the operator:
These are bit shift left and bit shift right operators. They are the same as in the C language and it's derivatives.
is x times 2 to the power of 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.
They are bitwise shift operators.
x << y
means x × 2y, whilex >> 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: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 −∞.
From the specification:
and a bit below: