How to use the bitwise right shift operator (>>) in Ruby

Overview

The operator >>, which is known as the bitwise right shift operator, is used to shift the bits of a particular number to the right by n positions.

For example, the binary representation of 4 is 0010. If we perform 4 >> 1, we move its bits by 1 position to the right. This results in 00010, which is 2 in base 10. Hence, 4 >> 1 is equal to 2.

Syntax

number >> shifts
Syntax for bitwise right shift operator

Parameters

number: This is the number whose bits we want to shift. 

shifts: This is the number of positions to shift the bits of number to the right.

Return value

The value returned is an integer. It is the equivalent to the number shifted right by shifts.

Example

# shift some bits of numbers
puts 200 >> 1
puts 70 >> 2
puts 10 >> 2
puts 5 >> 3
puts 4 >> 2

Explanation

In the code above, we use the bitwise right shift operator to shift the bits of some numbers and then we print the results to the console screen.

  • Line 2: Right shift 200 by 1 bit.
  • Line 3: Right shift 70 by 2 bits.
  • Line 4: Right shift 10 by 2 bits.
  • Line 5: Right shift 5 by 3 bits.
  • Line 6: Right shift 4 by 2 bits.

Free Resources