Go Reference ยท Operators
The << and >> shift operators
Reference for Go's shift operators << and >>: left and right shifts, arithmetic shifts on signed integers, shift counts, overflow and untyped constants.
x << n shifts the bits of x to the left by n places, filling with zeros on the right. x >> n shifts to the right. For unsigned integers the new left bits are zeros. For signed integers >> is an arithmetic shift: the sign bit is copied in, so negative numbers stay negative.
A left shift by n multiplies by 2^n (modulo the integer's size), and a right shift divides by 2^n rounding toward negative infinity. Shifts are the usual way to build bit flags, extract bit fields and compute powers of two.
flags := 1 << 3 // 8 half := 100 >> 1 // 50
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.
Syntax
x << n x >> n x <<= n x >>= n
| Name | Description |
|---|---|
x |
The left operand: must be an integer (or an untyped constant representable as one). The result has the type of x. |
n |
The shift count: an integer of any type, or an untyped constant that is non-negative and representable as uint. |
Edge cases
- A negative shift count in a non-constant expression causes a run-time panic. A constant negative count is a compile-time error.
- Shifting by the width of the type or more is allowed:
<<and unsigned>>give 0, and signed>>gives 0 or -1 depending on the sign. - Shift operators have the same precedence as
*,/,%,&and&^, which binds tighter than+and|.
Usage notes
- Shifts never panic on overflow. Bits that fall off the left end are discarded silently, so
uint8(200) << 1is 144. - Signed
>>rounds toward negative infinity (-7 >> 1is-4), while/truncates toward zero (-7 / 2is-3). - When the left operand is an untyped constant in a non-constant shift, its type comes from the context.
var f float64 = 1 << swith a variablesis a compile error because the constant would become a float. Writefloat64(1 << s)or use an integer variable first. 1 << nis the idiomatic way to write powers of two and bit masks. Combined withiotait declares flag sets, as in the second example.x &^ mask("and not") clears bits, a companion to shifts when working with flags.- Prefer unsigned types for bit manipulation; shifting signed values makes sign behavior part of your problem.
- The shift count does not need to be
uintsince Go 1.13. Any integer type works.