Skip to main content
The ~ operator is the unary bitwise complement operator. It performs a logical NOT operation on the binary representation of a number, inverting every bit so that each 0 becomes 1 and each 1 becomes 0.

Syntax

var result = ~expression;

Type Support

The operator is defined for the following types in the Dart core library:
  • int: Performs bitwise inversion on the platform-specific integer representation.
  • BigInt: Performs bitwise inversion on an arbitrarily large integer.
User-defined classes can support this operation by overloading operator ~().

Platform Semantics

The bit-width used for the operation depends on the compilation target. Dart Native (VM, Mobile, Desktop) The int type is a 64-bit two’s complement integer. The operator inverts all 64 bits. Dart Web (JavaScript) The int type maps to a JavaScript number (IEEE 754 double-precision float). When the ~ operator is applied:
  1. The operand is truncated to a 32-bit signed integer.
  2. The bits are inverted within this 32-bit range.
  3. The result is a 32-bit signed integer.
Note: Because of this truncation, applying ~ to an integer larger than 32 bits on the web will result in data loss before the inversion occurs.

Mathematical Relationship

For integers using two’s complement representation, the relationship between the effective operand xx and the result is defined by the following formula: x=(x)1\sim x = (-x) - 1 On Dart Web, this formula applies to the truncated 32-bit value, not necessarily the original operand if it exceeds 32 bits.
Operand (xx)Binary RepresentationComplement (x\sim x)Result Decimal
0...0000...1111-1
1...0001...1110-2
-1...1111...00000

Binary Visualization

The following example demonstrates the inversion of the integer 5 (binary ...0000 0101).
void main() {
  int x = 5;
  
  // Binary of 5:  ...0000 0101
  // Inverted:     ...1111 1010
  // Result is -6 in two's complement
  
  int result = ~x;

  print(result); // Output: -6
}
Master Dart with Deep Grasping Methodology!Learn More