The bitwise XOR operator, or the exclusive OR operator, compares the bits of two numbers and sets if and only if one of the operands is 1. It is represented by the caret symbol (^).
LHS ^ RHS
LHS: This is the integer on the left-hand side.RHS: This is the integer on the right-hand side.static func ^ (LHS: Int, RHS: Int) -> Int
The bitwise XOR operator returns 1 when the bits are different and 0 when the bits are the same.
The possible return values of ^ on different combinations of bits are summarized below:
LHS | RHS | LHS ^ RHS |
1 | 1 | 0 |
1 | 0 | 1 |
0 | 1 | 1 |
0 | 0 | 0 |
// declare two integer variablesvar firstNumber = 10 // binary: 1010var secondNumber = 20 // binary: 10100// perform bitwise XOR operationvar resultNumber = firstNumber ^ secondNumberprint(resultNumber) // 30. binary: 11110
firstNumber and secondNumber, and assign them the integer values 10 (1010 in binary) and 20 (10100 in binary), respectively.firstNumber and secondNumber are traversed bitwise, and the resulting bit is set to 1 if the individual bits are different. Otherwise, they're set to 0. The complete calculation is shown below:Free Resources