Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

ruby
bitwise
and
communitycreator

How to perform a bitwise AND operation in Ruby

okwudili onyejiaku

Overview

The bitwise AND operation allows multiplying the bits of numbers and returning the result in decimal format. To achieve this, we must use the operator &. This means that when we perform a bitwise AND operation on two numbers, say 2 and 1, this is what will happen:

  • The bits of 2 and 1 will be multiplied.

    0010 * 0001 = 0000

  • The result 0000 is equivalent to 0 . Hence, 2 & 1 is equal to 0.

Syntax

number1 & number2
Syntax for bitwise AND operator in Ruby

Parameters

number1 and number2: These are the numbers we want to get the decimal equivalent of multiplying their binaries.

Return value

The value returned is the decimal equivalent of the result returned by multiplying the bits of numbers number1 and number2.

Example

puts 2 & 1
puts 7 & 5
puts 10 & 3
puts 200 & 5
Performing a bitwise operation in Ruby

Explanation

In the code above:

  • Lines 1–4: We perform a bitwise AND operation on some numbers and print the results to the console.

RELATED TAGS

ruby
bitwise
and
communitycreator
RELATED COURSES

View all Courses

Keep Exploring