Skip to content

Bit Manipulation

Posted on:May 23, 2024 at 03:22 PM

JavaScript Bit Manipulation Cheat Sheet

To convert a number to its binary representation in JavaScript, you can use the toString method with a base of 2. Here’s how you can do it:

  let num = 5;
  let binaryString = num.toString(2);
  console.log(binaryString); // "101"

If you need a fixed-length binary string, you can pad the result with leading zeros:

let num = 5;
let binaryString = num.toString(2).padStart(8, '0');
console.log(binaryString); // "00000101"

Basic Operators

  1. AND (&)

    • Description: Returns a 1 in each bit position for which the corresponding bits of both operands are 1. The AND operator is commonly used for masking and checking the presence of specific bits.
    • Example: 5 & 30101 & 00110001 (1)
  2. OR (|)

    • Description: Returns a 1 in each bit position for which the corresponding bits of either operand are 1. The OR operator is useful for combining or merging bits.
    • Example: 5 | 30101 | 00110111 (7)
  3. XOR (^)

    • Description: Returns a 1 in each bit position for which the corresponding bits of either but not both operands are 1. The XOR operator is often used for toggling or swapping bits.
    • Example: 5 ^ 30101 ^ 00110110 (6)
  4. NOT (~)

    • Description: Inverts the bits of the operand (flips 0s to 1s and 1s to 0s). This operator is useful for inverting the bits of a number.
    • Example: ~5~01011010 (Note: in JavaScript, the result is signed and depends on the bit length.)

Shift Operators

  1. Left Shift (<<)

    • Description: Shifts the bits of the operand to the left by the specified number of positions. This operation is equivalent to multiplying the number by 2 raised to the power of the shift amount. It is frequently used for efficient multiplication or creating space for additional bits.
    • Example: 5 << 20101 << 210100 (20)
  2. Sign-Propagating Right Shift (>>)

    • Description: Shifts the bits of the operand to the right by the specified number of positions, preserving the sign. This operation is equivalent to dividing the number by 2 raised to the power of the shift amount. It is commonly used for efficient division or extracting specific bits.
    • Example: 5 >> 10101 >> 10010 (2)
  3. Zero-Fill Right Shift (>>>)

    • Description: Shifts the bits of the operand to the right by the specified number of positions, filling with zeros.
    • Example: 5 >>> 10101 >>> 10010 (2)

Common Bit Manipulation Tasks

  1. Check if a number is even or odd

    • Description: Use the AND operator with 1.
    • Example: num & 10 (even), 1 (odd)
    • Code:
      function isOdd(num) {
          return (num & 1) === 1;
      }
  2. Set a specific bit

    • Description: Use the OR operator with a bit mask.
    • Example: To set the 2nd bit of 5 (0101):
    • Code:
      function setBit(num, bitPosition) {
          return num | (1 << bitPosition);
      }
  3. Clear a specific bit

    • Description: Use the AND operator with a NOT bit mask.
    • Example: To clear the 2nd bit of 5 (0101):
    • Code:
      function clearBit(num, bitPosition) {
          return num & ~(1 << bitPosition);
      }
  4. Toggle a specific bit

    • Description: Use the XOR operator with a bit mask.
    • Example: To toggle the 2nd bit of 5 (0101):
    • Code:
      function toggleBit(num, bitPosition) {
          return num ^ (1 << bitPosition);
      }
  5. Check if a specific bit is set

    • Description: Use the AND operator with a bit mask.
    • Example: To check the 2nd bit of 5 (0101):
    • Code:
      function isBitSet(num, bitPosition) {
          return (num & (1 << bitPosition)) !== 0;
      }
  6. Count the number of 1s (Hamming weight)

    • Description: Use a loop or the built-in toString(2) and match method.
    • Code:
      function countSetBits(num) {
          let count = 0;
          while (num) {
              count += num & 1;
              num >>= 1;
          }
          return count;
      }
      
      // Alternatively
      function countSetBits(num) {
          return num.toString(2).split('0').join('').length;
      }
  7. Flip all bits

    • Description: Use the NOT operator.
    • Example: To flip all bits of 5 (0101):
    • Code:
      function flipBits(num) {
          return ~num;
      }