How to perform bitwise XOR operation in Swift
Overview
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 (^).
Syntax
LHS ^ RHS
Parameters
LHS: This is the integer on the left-hand side.RHS: This is the integer on the right-hand side.
Return value
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 |
Example
// declare two integer variablesvar firstNumber = 10 // binary: 1010var secondNumber = 20 // binary: 10100// perform bitwise XOR operationvar resultNumber = firstNumber ^ secondNumberprint(resultNumber) // 30. binary: 11110
Explanation
- Lines 2–3: We declare two new variables,
firstNumberandsecondNumber, and assign them the integer values10(1010in binary) and20(10100in binary), respectively. - Line 6: We perform the bitwise XOR operation.
firstNumberandsecondNumberare traversed bitwise, and the resulting bit is set to1if the individual bits are different. Otherwise, they're set to0. The complete calculation is shown below:
Free Resources
Copyright ©2026 Educative, Inc. All rights reserved