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 variables
var firstNumber = 10 // binary: 1010
var secondNumber = 20 // binary: 10100
// perform bitwise XOR operation
var resultNumber = firstNumber ^ secondNumber
print(resultNumber) // 30. binary: 11110

Explanation

  • Lines 2–3: We declare two new variables, firstNumber and secondNumber, and assign them the integer values 10 (1010 in binary) and 20 (10100 in binary), respectively.
  • Line 6: We perform the bitwise XOR operation. 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:
Bitwise XOR operation of two integers, 10 and 20

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved