How to perform a bitwise AND operation in Ruby
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
2and1will be multiplied.
0010 * 0001 = 0000
- The result
0000is equivalent to0. Hence,2 & 1is equal to0.
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 & 1puts 7 & 5puts 10 & 3puts 200 & 5
Explanation
In the code above:
- Lines 1–4: We perform a bitwise AND operation on some numbers and print the results to the console.