Data Structure and Algorithm
Algorithms
Bitwise Algorithms
Bit Algorithms | Important Tactics

Bit Algorithms | Important Tactics

Having already discussed the first three bitwise operators — AND (&), OR (|), and XOR (^) — we now move on to the next two important operators: Bitwise NOT (~) and Bitwise Left Shift (<<).


4. Bitwise NOT (~) — Negation Operator

  • Flips all bits of a number (0 becomes 1, and 1 becomes 0).
  • Inverts the 32-bit binary representation of the number.

Example 1: x = 1

let x = 1;
console.log(~x); // Output: -2

Why?

  • Binary of 1 (32-bit): 00000000 00000000 00000000 00000001
  • Flipping all bits: 11111111 11111111 11111111 11111110
  • Two's Complement: In JavaScript, bitwise operations interpret numbers as 32-bit signed integers in two's complement representation. The leading 1 denotes a negative number, resulting in -2.

Two's Complement Rule: For any integer n, the bitwise NOT operation is equivalent to: ~n = -(n + 1)

  • For x = 1: ~1 = -(1 + 1) = -2
  • For x = 5: ~5 = -(5 + 1) = -6

Example 2: x = 5

let x = 5; // Binary: 000...0101
console.log(~x); // Output: -6

Why?

  • Binary of 5: 00000000 00000000 00000000 00000101
  • After flipping: 11111111 11111111 11111111 11111010
  • Result: -6

5. Bitwise Left Shift (<<)

  • Shifts bits to the left by the specified number of positions.
  • Appends 0s at the end.
  • Each shift to the left is equivalent to multiplying the number by 2.

Example 1: x = 3; x << 1

let x = 3;
console.log(x << 1); // Output: 6

Explanation:

  • Binary of 3: 00000000 00000000 00000000 00000011
  • Shifted left by 1: 00000000 00000000 00000000 00000110 (which is 6 in decimal)

Example 2: x = 3; x << 2

let x = 3;
console.log(x << 2); // Output: 12

Explanation:

  • Shifted left by 2: 00000000 00000000 00000000 00001100 (which is 12 in decimal)

Example 3: x = 3; x << 3

let x = 3;
console.log(x << 3); // Output: 24

Explanation:

  • Shifted left by 3: 00000000 00000000 00000000 00011000 (which is 24 in decimal)

Mathematical Rule: Shifting x left by y bits (x << y) is mathematically equivalent to: x * 2^y

  • 3 << 1 is equivalent to 3 * 2^1 = 6
  • 3 << 2 is equivalent to 3 * 2^2 = 12
  • 3 << 3 is equivalent to 3 * 2^3 = 24