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: -2Why?
- 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
1denotes 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: -6Why?
- 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: 6Explanation:
- Binary of
3:00000000 00000000 00000000 00000011 - Shifted left by 1:
00000000 00000000 00000000 00000110(which is6in decimal)
Example 2: x = 3; x << 2
let x = 3;
console.log(x << 2); // Output: 12Explanation:
- Shifted left by 2:
00000000 00000000 00000000 00001100(which is12in decimal)
Example 3: x = 3; x << 3
let x = 3;
console.log(x << 3); // Output: 24Explanation:
- Shifted left by 3:
00000000 00000000 00000000 00011000(which is24in decimal)
Mathematical Rule:
Shifting x left by y bits (x << y) is mathematically equivalent to:
x * 2^y
3 << 1is equivalent to3 * 2^1 = 63 << 2is equivalent to3 * 2^2 = 123 << 3is equivalent to3 * 2^3 = 24