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
The right shift operator ( >> ) returns the signed number represented by the result of performing a sign-extending shift of the binary representation of the first operand (evaluated as a two's complement bit string) to the right by the number of bits, modulo 32, specified in the second operand.
>> Indicates the bits are to be shifted to the right. Each operand must have an integral or enumeration type. The compiler performs integral promotions on the operands, and then the right operand is converted to type int .
The >> operator shifts its left-hand operand right by the number of bits defined by its right-hand operand. For information about how the right-hand operand defines the shift count, see the Shift count of the shift operators section.
'=='(Equal To) operator checks whether the two given operands are equal or not. If so, it returns true. Otherwise, it returns false. For example, 5==5 will return true. '!
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 −∞.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With