Skip to main content
The ~ operator in Dart is the unary bitwise NOT operator, also known as the bitwise complement operator. It evaluates its operand by inverting every bit in its binary representation, flipping all 0s to 1s and all 1s to 0s. Because Dart represents signed integers using two’s complement, applying the bitwise NOT operator to any integer n mathematically yields -(n + 1).
var result = ~operand;

Bitwise Mechanics

When the ~ operator evaluates an integer, it processes the value at the hardware level based on the platform’s integer size (64-bit on the Dart Native VM, 32-bit when compiled to JavaScript). For example, evaluating ~5:
  1. The integer 5 is represented in binary as ...0000000000000101.
  2. The ~ operator applies a logical negation to each individual bit.
  3. The resulting binary is ...1111111111111010.
  4. In two’s complement architecture, this binary sequence represents the decimal value -6.
void main() {
  int a = 5;
  int b = ~a; 
  
  print(b); // Outputs: -6
  
  int c = -12;
  int d = ~c;
  
  print(d); // Outputs: 11
}

Type Constraints and Overloading

In the Dart core library, the ~ operator is defined as an instance method on the int and BigInt classes. Attempting to apply it to a double or a generic num (unless explicitly cast or statically inferred as int) will result in a compile-time error. However, Dart supports operator overloading, meaning the ~ operator can be implemented on any custom class by defining operator ~.
int intResult = ~42;               // Valid
BigInt bigIntResult = ~BigInt.one; // Valid

// double invalid = ~42.0;         // Compile-time error: The operator '~' isn't defined for the type 'double'.

class BitMask {
  final int _mask;
  BitMask(this._mask);

  // Overloading the unary bitwise NOT operator
  BitMask operator ~() => BitMask(~_mask);
}

Operator Precedence

As a unary prefix operator, ~ has a lower precedence level than unary postfix operators (such as expr++, [], ., (), and the null assertion operator !). However, it maintains a higher precedence than multiplicative, additive, shift, and binary bitwise operators. It will evaluate before these lower-precedence operators unless explicitly overridden by parentheses.
int result = ~5 + 2; // Evaluates as (~5) + 2, resulting in -6 + 2 = -4
Tired of Poor Dart Skills? Fix That With Deep Grasping!Learn More