Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

ruby
bitwise
left shift
communitycreator

How to use the bitwise left shift operator (<<) in Ruby

okwudili onyejiaku

Overview

In Ruby, the bitwise left shift operator shifts each bit of a number to the left by n positions.

For a better understanding, see the diagram below:

Left shift 2 by 1 bit

Syntax

number << shifts
Syntax for bitwise left shift operator

Parameters

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

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

Return value

The value returned is an integer. It is equivalent to the decimal value of the number after shifting the bits.

Example

# shift some bits of numbers
puts 2 << 1
puts 7 << 2
puts 1 << 2
puts 5 << 3
Code example for performing bitwise left shift operation

Explanation

In the code above:

  • Lines 2–5: We use the bitwise left shift operator to shift the bits of some numbers and then we print the results to the console screen.

RELATED TAGS

ruby
bitwise
left shift
communitycreator
RELATED COURSES

View all Courses

Keep Exploring