~ 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).
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:
- The integer
5is represented in binary as...0000000000000101. - The
~operator applies a logical negation to each individual bit. - The resulting binary is
...1111111111111010. - In two’s complement architecture, this binary sequence represents the decimal value
-6.
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 ~.
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.
Tired of Poor Dart Skills? Fix That With Deep Grasping!Learn More





