Skip to main content

JavaScript Bitwise Operations

The bitwise operators are used to perform operations on the binary representation of numbers.

These operators are useful when dealing with low-level data manipulation, such as bit masks, data compression, and cryptography.

There are several bitwise operators in JavaScript:

  • Bitwise AND (&): Returns a 1 in each bit position for which the corresponding bits of both operands are 1's.

  • Bitwise OR (|): Returns a 1 in each bit position for which the corresponding bits of either or both operands are 1's.

  • Bitwise XOR (^): Returns a 1 in each bit position for which the corresponding bits of either but not both operands are 1's.

  • Bitwise NOT (~): Inverts the bits of its operand, converting 0's to 1's and vice versa.

  • Left shift (<<): Shifts the bits of its left operand to the left by the number of positions specified by the right operand. Zeros are shifted in from the right.

  • Sign-propagating right shift (>>): Shifts the bits of its left operand to the right by the number of positions specified by the right operand, preserving the sign of the original number. Zeros are shifted in from the left.

  • Zero-fill right shift (>>>): Shifts the bits of its left operand to the right by the number of positions specified by the right operand, filling in zeros from the left.

Some example of using some of these operators:

const num1 = 10; // binary: 1010
const num2 = 6; // binary: 0110

const andResult = num1 & num2; // 2 (binary: 0010)
const orResult = num1 | num2; // 14 (binary: 1110)
const xorResult = num1 ^ num2; // 12 (binary: 1100)
const notResult = ~num1; // -11 (binary: 11111111111111111111111111110101)
const leftShiftResult = num1 << 2; // 40 (binary: 101000)
const rightShiftResult = num1 >> 1; // 5 (binary: 0101)
const zeroFillRightShiftResult = num1 >>> 1; // 5 (binary: 0101)

The bitwise operations are performed on the 32-bit binary representation of numbers in JavaScript. When using bitwise operators, JavaScript implicitly converts operands to 32-bit signed integers.