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 numbersputs 200 >> 1puts 70 >> 2puts 10 >> 2puts 5 >> 3puts 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
200by1bit. - Line 3: Right shift
70by2bits. - Line 4: Right shift
10by2bits. - Line 5: Right shift
5by3bits. - Line 6: Right shift
4by2bits.