GeezerVisonThe World Wide Web, restored to 800 pixels of glory. | ||||||||
| Home|About|Gaming cabinet|Archives|How it works|Starter sites | ||||||||
GeezerVison is showing developer.mozilla.org — Bitwise NOT (~) - JavaScript | MDN Bitwise NOT (~)
|
| x | NOT x |
|---|---|
| 0 | 1 |
| 1 | 0 |
9 (base 10) = 00000000000000000000000000001001 (base 2)
--------------------------------
~9 (base 10) = 11111111111111111111111111110110 (base 2) = -10 (base 10)
Bitwise NOTing any 32-bit integer x yields -(x + 1). For example, ~-5 yields 4.
Numbers with more than 32 bits get their most significant bits discarded. For example, the following integer with more than 32 bits will be converted to a 32-bit integer:
Before: 11100110111110100000000000000110000000000001 After: 10100000000000000110000000000001
Warning:
You may see people using ~~ to truncate numbers to integers. Bitwise NOTing any number x twice returns x converted to a 32-bit integer, which additionally removes leading bits for numbers outside the range -2147483648 to 2147483647. Use Math.trunc() instead.
For BigInts, there's no truncation. Conceptually, understand positive BigInts as having an infinite number of leading 0 bits, and negative BigInts having an infinite number of leading 1 bits.
~0; // -1
~-1; // 0
~1; // -2
~0n; // -1n
~4294967295n; // -4294967296n
| Specification |
|---|
| ECMAScript® 2027 Language Specification # sec-bitwise-not-operator |