Movatterモバイル変換


[0]ホーム

URL:


MDN Web Docs

Bitwise NOT (~)

BaselineWidely available

Thebitwise NOT (~) operator returns a number or BigInt whose binary representation has a1 in each bit position for which the corresponding bit of the operand is0, and a0 otherwise.

Try it

const a = 5; // 00000000000000000000000000000101const b = -3; // 11111111111111111111111111111101console.log(~a); // 11111111111111111111111111111010// Expected output: -6console.log(~b); // 00000000000000000000000000000010// Expected output: 2

Syntax

js
~x

Description

The~ operator is overloaded for two types of operands: number andBigInt. For numbers, the operator returns a 32-bit integer. For BigInts, the operator returns a BigInt. It firstcoerces the operand to a numeric value and tests the type of it. It performs BigInt NOT if the operand becomes a BigInt; otherwise, it converts the operand to a32-bit integer and performs number bitwise NOT.

The operator operates on the operands' bit representations intwo's complement. The operator is applied to each bit, and the result is constructed bitwise.

The truth table for the NOT operation is:

xNOT x
01
10
 9 (base 10) = 00000000000000000000000000001001 (base 2)               --------------------------------~9 (base 10) = 11111111111111111111111111110110 (base 2) = -10 (base 10)

Bitwise NOTing any 32-bit integerx yields-(x + 1). For example,~-5 yields4.

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: 11100110111110100000000000000110000000000001After:              10100000000000000110000000000001

Warning:You may see people using~~ to truncate numbers to integers. Bitwise NOTing any numberx twice returnsx converted to a 32-bit integer, which additionally removes leading bits for numbers outside the range -2147483648 to 2147483647. UseMath.trunc() instead.

For BigInts, there's no truncation. Conceptually, understand positive BigInts as having an infinite number of leading0 bits, and negative BigInts having an infinite number of leading1 bits.

Examples

Using bitwise NOT

js
~0; // -1~-1; // 0~1; // -2~0n; // -1n~4294967295n; // -4294967296n

Specifications

Specification
ECMAScript® 2026 Language Specification
# sec-bitwise-not-operator

Browser compatibility

See also

Help improve MDN

Learn how to contribute.

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2025 Movatter.jp