JAVASCRIPT Tutorial

Bitwise Operators

Bitwise operators are used to perform operations on individual bits of numbers. They include:

Bitwise AND (&)

  • Computes a bitwise AND of two numbers, resulting in a 1 only if both corresponding bits are 1s.

Bitwise OR (|)

  • Computes a bitwise OR of two numbers, resulting in a 1 if either corresponding bit is a 1.

Bitwise XOR (^)

  • Computes a bitwise XOR of two numbers, resulting in a 1 only if the corresponding bits are different.

Bitwise NOT (~)

  • Inverts the bits of a number, resulting in 0s becoming 1s and 1s becoming 0s.

Left Shift (<<)

  • Shifts the bits of a number to the left by the specified number of bits, filling empty bits with 0s.

Right Shift (>>)

  • Shifts the bits of a number to the right by the specified number of bits, filling empty bits with 0s.

Unsigned Right Shift (>>>)

  • Similar to right shift, but fills empty bits with 0s regardless of the sign bit.

JavaScript Example:

const a = 10; // 1010 in binary
const b = 5;  // 0101 in binary

console.log(a & b); // 0000 (AND: both bits must be 1)
console.log(a | b); // 1111 (OR: either bit is 1)
console.log(a ^ b); // 1111 (XOR: bits must be different)
console.log(~a); // 1101 (NOT: inverts bits)
console.log(a << 2); // 101000 (Left shift: adds 0s)
console.log(a >> 2); // 0010 (Right shift: loses 1s)
console.log(a >>> 2); // 0010 (Unsigned right shift: loses 0s)