Reputation: 11900
I was following 'A tour of GO` on http://tour.golang.org. The table 15 has some code that I cannot understand. It defines two constants with the following syntax:
const (
Big = 1<<100
Small = Big>>99
)
And it's not clear at all to me what it means. I tried to modify the code and run it with different values, to record the change, but I was not able to understand what is going on there.
Then, it uses that operator again on table 24. It defines a variable with the following syntax:
MaxInt uint64 = 1<<64 - 1
And when it prints the variable, it prints:
uint64(18446744073709551615)
Where uint64
is the type. But I can't understand where 18446744073709551615
comes from.
Upvotes: 3
Views: 208
Reputation: 11476
It's a logical shift:
every bit in the operand is simply moved a given number of bit positions, and the vacant bit-positions are filled in, usually with zeros
<< left shift integer << unsigned integer
>> right shift integer >> unsigned integer
Upvotes: 1
Reputation: 25874
They are Go's bitwise shift operators.
Here's a good explanation of how they work for C (they work in the same way in several languages).
Basically 1<<64 - 1
corresponds to 2^64 -1, = 18446744073709551615.
Think of it this way. In decimal if you start from 001 (which is 10^0) and then shift the 1 to the left, you end up with 010, which is 10^1. If you shift it again you end with 100, which is 10^2. So shifting to the left is equivalent to multiplying by 10 as many times as the times you shift.
In binary it's the same thing, but in base 2, so 1<<64 means multiplying by 2 64 times (i.e. 2 ^ 64).
Upvotes: 11
Reputation: 382454
That's the same as in all languages of the C family : a bit shift.
See http://en.wikipedia.org/wiki/Bitwise_operation#Bit_shifts
This operation is commonly used to multiply or divide an unsigned integer by powers of 2 :
b := a >> 1 // divides by 2
1<<100
is simply 2^100
(that's Big).
1<<64-1
is 2⁶⁴-1, and that's the biggest integer you can represent in 64 bits (by the way you can't represent 1<<64
as a 64 bits int and the point of table 15 is to demonstrate that you can have it in numerical constants anyway in Go).
Upvotes: 7
Reputation: 1699
The >> and << are logical shift operations. You can see more about those here:
http://en.wikipedia.org/wiki/Logical_shift
Also, you can check all the Go operators in their webpage
Upvotes: 1