Skip to main content
The ^ operator functions as a binary operator that performs a bitwise exclusive OR (XOR) on int operands and a logical exclusive OR on bool operands.

Integer Bitwise XOR

When applied to operands of type int, the operator compares the binary representation of the numbers bit by bit. For each bit position, the resulting bit is set to 1 if the corresponding bits of the operands differ, and 0 if they are identical. The return value is a new int. Bitwise Truth Table:
Bit ABit BResult (A ^ B)
000
011
101
110
Syntax:
int result = operand1 ^ operand2;
Example:
void main() {
  // Binary: 0101 (Decimal 5)
  // Binary: 0011 (Decimal 3)
  // ---------------------
  // Result: 0110 (Decimal 6)
  
  int a = 5;
  int b = 3;
  int result = a ^ b;
  
  print(result); // Output: 6
}

Boolean Logical XOR

When applied to operands of type bool, the ^ operator evaluates to true if exactly one of the operands is true. If both operands are true or both are false, the expression evaluates to false. This is functionally equivalent to the inequality operator (!=) for booleans. Syntax:
bool result = condition1 ^ condition2;
Example:
void main() {
  bool x = true;
  bool y = false;
  bool z = true;

  print(x ^ y); // Output: true  (Operands differ)
  print(x ^ z); // Output: false (Operands are identical)
}

Compound Assignment

The compound assignment operator ^= performs the XOR operation on the variable and the operand, then assigns the resulting value back to the variable.
int a = 5; // Binary: 0101
a ^= 3;    // Binary: 0011
// a is now 6 (Binary: 0110)

Operator Precedence

The ^ operator follows specific precedence rules within the Dart expression hierarchy:
  1. Lower precedence than: Bitwise AND (&), shift operators (<<, >>, >>>), and arithmetic operators (+, *).
  2. Higher precedence than: Bitwise OR (|), relational operators (<, >), and equality operators (==, !=).
Due to this hierarchy, the expression a ^ b == c is evaluated as (a ^ b) == c.

Distinction from Exponentiation

The ^ operator is not used for exponentiation in Dart. Attempting to use it for powers (e.g., 2 ^ 3) will result in a bitwise XOR operation. To calculate powers, use the pow() function from the dart:math library.
Master Dart with Deep Grasping Methodology!Learn More