How to perform a bitwise AND operation in Swift
Overview
In Swift, we can perform a bitwise AND operation using the ampersand & operator. This operator requires two operands. It gets the binary representation of the operands, multiplies them, and returns the result as a decimal.
Syntax
num1 & num2
Syntax for Bitwise AND(&) operation
Parameters
num1andnum2: These are the number values on which we want to perform a bitwise AND operation.
Return value
This method returns the decimal equivalent of multiplying the bits of num1 and num2.
Example
Let's look at the code below:
// create some valuesvar num1 = 3var num2 = 2var num3 = 100var num4 = 20var num5 = 1var num6 = 0// perform AND operationprint(num1 & num2) // 2print(num3 & num4) // 4print(num5 & num6) // 0
Explanation
- Lines 2 to 7: We create some variables.
- Lines 10 to 12: We use the AND operator (
&) and perform a bitwise AND operation on the values we created. We print the results to the console.