Welcome to the fascinating world of Bitwise Operators! Let's embark on a journey to understand this powerful tool in programming. We'll cover everything from the basics to advanced examples, making it easy for both beginners and intermediates to grasp.
Bitwise operators manipulate individual bits within an integer or binary number. They are crucial for low-level programming, optimizing code, and solving specific problems that require bit-level manipulation.
To begin, let's understand binary numbers and their significance in bitwise operations. A binary number is a base-2 number system consisting of 0s and 1s.
Binary: 10101010
Decimal: 180 (calculated by adding the value of each bit)
There are six primary bitwise operators in JavaScript:
& (Bitwise AND)| (Bitwise OR)^ (Bitwise XOR)~ (Bitwise NOT)<< (Bitwise Left Shift)>> (Bitwise Right Shift)&) š”The & operator performs a bitwise AND operation, where both bits must be 1 for the result to be 1.
// Example 1: 5 (101) AND 3 (011)
console.log(5 & 3); // Output: 1 (001)|) š”The | operator performs a bitwise OR operation, where either bit can be 1 for the result to be 1.
// Example 1: 5 (101) OR 3 (011)
console.log(5 | 3); // Output: 7 (111)^) š”The ^ operator performs a bitwise XOR operation, where the result is 1 if the bits are different and 0 if they are the same.
// Example 1: 5 (101) XOR 3 (011)
console.log(5 ^ 3); // Output: 6 (110)~) š”The ~ operator takes the bitwise complement of the number, changing all 1s to 0s and all 0s to 1s.
// Example 1: Bitwise NOT of 5 (101)
console.log(~5); // Output: -6 (1101100)<<) š”The << operator shifts the bits of a number to the left by the specified number of positions. The vacated bits are filled with zeros.
// Example 1: Shifting 5 (101) 2 positions to the left
console.log(5 << 2); // Output: 20 (1010000)>>) š”The >> operator shifts the bits of a number to the right by the specified number of positions. The vacated leftmost bits are filled with zeros (arithmetic right shift), and with sign bits (logical right shift).
// Example 1: Arithmetic right shift of 5 (101) 2 positions
console.log(5 >> 2); // Output: 1 (01)
// Example 2: Logical right shift of -5 (-1011) 2 positions
console.log(-5 >>> 2); // Output: -13 (100011)Bitwise operators are essential for various real-world scenarios, such as:
Bitwise operators might seem complex initially, but with practice and understanding, they become an indispensable tool in your programming arsenal. Mastering bitwise operators will not only help you solve intricate problems but also make your code more efficient and secure.
What does the `&` operator do in JavaScript?
What is the result of the operation `5 & 3` in JavaScript?