按位非 (~)

按位 NOT (~) 运算符返回一个数字或 BigInt,其二进制表示形式在每个位位置都有 1,操作数的相应位为 0,否则为 0

¥The bitwise NOT (~) operator returns a number or BigInt whose binary representation has a 1 in each bit position for which the corresponding bit of the operand is 0, and a 0 otherwise.

Try it

语法

¥Syntax

js
~x

描述

¥Description

~ 运算符针对两种类型的操作数进行重载:编号和 BigInt。对于数字,该运算符返回一个 32 位整数。对于 BigInts,该运算符返回一个 BigInt。它首先 将操作数强制为数值 并测试它的类型。如果操作数变为 BigInt,则执行 BigInt NOT;否则,它将操作数转换为 32 位整数 并执行数字按位 NOT。

¥The ~ operator is overloaded for two types of operands: number and BigInt. For numbers, the operator returns a 32-bit integer. For BigInts, the operator returns a BigInt. It first coerces 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 a 32-bit integer and performs number bitwise NOT.

该运算符对 二进制补码 中操作数的位表示进行运算。该运算符应用于每一位,并按位构造结果。

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

NOT 运算的真值表为:

¥The truth table for the NOT operation is:

x 不是 x
0 1
1 0
 9 (base 10) = 00000000000000000000000000001001 (base 2)
               --------------------------------
~9 (base 10) = 11111111111111111111111111110110 (base 2) = -10 (base 10)

超过 32 位的数字将丢弃其最高有效位。例如,以下超过 32 位的整数将被转换为 32 位整数:

¥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

对于 BigInts,没有截断。从概念上讲,将正 BigInt 理解为具有无限数量的前导 0 位,将负 BigInt 理解为具有无限数量的前导 1 位。

¥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.

按位对任何 32 位整数 x 进行 NOT 运算会得到 -(x + 1)。例如,~-5 产生 4

¥Bitwise NOTing any 32-bit integer x yields -(x + 1). For example, ~-5 yields 4.

对任意数字 x 进行按位取反两次会返回转换为 32 位整数的 x。不要使用 ~~x 将数字截断为整数;使用 Math.trunc() 代替。由于数字使用 32 位表示,~-1~4294967295 (232 - 1) 都会生成 0

¥Bitwise NOTing any number x twice returns x converted to a 32-bit integer. Do not use ~~x to truncate numbers to integers; use Math.trunc() instead. Due to using 32-bit representation for numbers, both ~-1 and ~4294967295 (232 - 1) result in 0.

示例

¥Examples

使用按位 NOT

¥Using bitwise NOT

js
~0; // -1
~-1; // 0
~1; // -2

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

规范

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

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看