Movatterモバイル変換


[0]ホーム

URL:


MDN Web Docs

Bitwise XOR (^)

BaselineWidely available

Thebitwise XOR (^) operator returns a number or BigInt whose binary representation has a1 in each bit position for which the corresponding bits of either but not both operands are1.

Try it

const a = 5; // 00000000000000000000000000000101const b = 3; // 00000000000000000000000000000011console.log(a ^ b); // 00000000000000000000000000000110// Expected output: 6

Syntax

js
x ^ y

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 both operands to numeric values and tests the types of them. It performs BigInt XOR if both operands become BigInts; otherwise, it converts both operands to32-bit integers and performs number bitwise XOR. ATypeError is thrown if one operand becomes a BigInt but the other becomes a number.

The operator operates on the operands' bit representations intwo's complement. Each bit in the first operand is paired with the corresponding bit in the second operand:first bit tofirst bit,second bit tosecond bit, and so on. The operator is applied to each pair of bits, and the result is constructed bitwise.

The truth table for the XOR operation is:

xyx XOR y
000
011
101
110
     9 (base 10) = 00000000000000000000000000001001 (base 2)    14 (base 10) = 00000000000000000000000000001110 (base 2)                   --------------------------------14 ^ 9 (base 10) = 00000000000000000000000000000111 (base 2) = 7 (base 10)

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^ 0 to truncate numbers to integers. Bitwise XORing any numberx with0 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 XOR

js
// 9  (00000000000000000000000000001001)// 14 (00000000000000000000000000001110)14 ^ 9;// 7  (00000000000000000000000000000111)14n ^ 9n; // 7n

Specifications

Specification
ECMAScript® 2026 Language Specification
# prod-BitwiseXORExpression

Browser compatibility

See also

Help improve MDN

Learn how to contribute.

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2025 Movatter.jp