Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

The >> operator is the bitwise right shift operator in Go. It shifts the binary representation of the left operand to the right by the number of bit positions specified by the right operand.
result := x >> n

Operand Constraints

  • Left Operand (x): Must be of an integer type (signed or unsigned) or an untyped constant representable as an integer.
  • Right Operand (n): Must be of an integer type or an untyped constant representable as an unsigned integer. Shifting by a negative count results in a compile-time error or a runtime panic.

Shift Mechanics

Go determines the type of right shift to perform based on the underlying type of the left operand. There is no separate logical right shift operator (like >>> in Java); instead, Go uses the type system to dictate behavior.

1. Unsigned Integers (Logical Right Shift)

If the left operand is an unsigned integer (e.g., uint, uint8, uint16), Go performs a logical right shift. The bits are shifted to the right, and the vacated Most Significant Bits (MSBs) on the left are filled with zeros (0).
var x uint8 = 200     // Binary: 11001000
result := x >> 3      // Binary: 00011001 (Decimal: 25)

2. Signed Integers (Arithmetic Right Shift)

If the left operand is a signed integer (e.g., int, int8, int16), Go performs an arithmetic right shift. The bits are shifted to the right, but the vacated MSBs are filled with a copy of the original sign bit. This preserves the sign of the number (Two’s complement representation).
  • If the number is positive (sign bit 0), vacated bits are filled with 0.
  • If the number is negative (sign bit 1), vacated bits are filled with 1.
var positive int8 = 120    // Binary: 01111000
resPos := positive >> 2    // Binary: 00011110 (Decimal: 30)

var negative int8 = -120   // Binary: 10001000
resNeg := negative >> 2    // Binary: 11100010 (Decimal: -30)

Mathematical Equivalence

Mathematically, shifting an integer x right by n positions is equivalent to integer division by 2n2^n, rounded towards negative infinity: xn=x2nx \gg n = \lfloor \frac{x}{2^n} \rfloor

Out-of-Bounds Shifts

If the right operand n is greater than or equal to the size of the left operand in bits:
  • For unsigned integers, the result is always 0.
  • For signed integers, the result is 0 if the original number was positive, and -1 (all bits set to 1) if the original number was negative.
var x uint8 = 255
result := x >> 8 // Result: 0 (Binary: 00000000)

var y int8 = -128
result2 := y >> 8 // Result: -1 (Binary: 11111111)
Master Go with Deep Grasping Methodology!Learn More