SoFunction
Updated on 2025-04-12

JavaScript bit operations and practical application examples

Bit operation basics

During bit operation, all operands are considered as 32-bit complement binary strings. If 0 is not enough, the most significant bit will be discarded. The calculation result is also returned in the form of complement inversion

&: bit AND. The result value of the bit is 1 only if both operands correspond to 1. For example:

const a = 120; // 0b000...1111000
const b = 11; //  0b000...0001011
a & b; // 8 = 0b000...1000
  • &=: bit AND assignment. Two operands perform bit AND operation and assign the result to the first operand

|: bit OR. As long as one of the corresponding bits of the two operands is 1, the result value of the bit is 1. For example:

const a = 5; // 0b000...0101
const b = 3; // 0b000...0011
a | b; // 7 = 0b000...0111
  • |=: Bit OR assignment. Two operands perform bit OR operations and assign the result to the first operand

^: bit XOR. When only one of the corresponding bits of the two operands is 1, the result value of the bit is 1. For example:

const a = 5; // 0b000...0101
const b = 3; // 0b000...0011
a ^ b; // 6 = 0b000...0110
  • ^=: Bit XOR assignment. Two operands perform bit XOR operation and assign the result to the first operand
  • ~: bit NOT. Inverse the operand bit by bit. The calculation result satisfies~x === -(x+1)

<<: left shift. Move the first operand to the left by the specified bit. The left side move out position is discarded, and the right side more exit position is supplemented by 0. For example:

const a = 9; // 0b000...001001
const b = 2;
a << b; // 36 = 0b000...100100

>>: Signed right shift. Move the first operand to the right the specified bit. The right move out position is discarded, and the left extra position is filled by the original lvalue

const a = 36; // 0b000...100100
const b = 2;
a >> b; // 9  =  0b000...001001
  • >>>: Unsigned right shift. Move the first operand to the right the specified bit. The right move out position is discarded, and the left move out position is supplemented by 0

Practical application

Determine whether an integer is a power of 2

function isPowerOfTwo(n) {
    return n > 0 && ((n - 1) & n) === 0;
}

Judge integer parity

function isOdd(n) {
    return (n & 1) === 1;
}

Sign judgment

const canFly = 1 &lt;&lt; 0;
const canRun = 1 &lt;&lt; 1;
const canSwim = 1 &lt;&lt; 2;
const canJump = 1 &lt;&lt; 3;
let flags = 0;
// Add a flagflags |= canFly;
flags |= canJump;
// Judgment sign!!(flags &amp; canFly); // true
!!(flags &amp; canJump); // true
// Clear the signflags &amp;= ~canFly;
!!(flags &amp; canFly); // false

The above is the detailed content of JavaScript bit operations and practical applications. For more information about JavaScript bit operations and practical applications, please pay attention to my other related articles!