JavaScript Bitwise Operations
JavaScript, a versatile and widely-used programming language, offers a set of powerful bitwise operations that often remain underutilized or overlooked by developers. In this article, we will delve into the world of JavaScript bitwise operations, exploring their functionality and providing practical examples to showcase their relevance in various scenarios.
Bitwise AND (&) Operation:
The bitwise AND operation compares each bit of two numbers and returns a new number with bits set to 1 only if the corresponding bits of both numbers are 1. Let’s consider an example:
let num1 = 5; // Binary: 0101
let num2 = 3; // Binary: 0011
let result = num1 & num2;
console.log(result); // Output: 1 (Binary: 0001)
In this example, the bitwise AND operation sets the bits to 1 only where both num1
and num2
have a corresponding bit set to 1.
Bitwise OR (|) Operation:
The bitwise OR operation compares each bit of two numbers and returns a new number with bits set to 1 if at least one of the corresponding bits in the original numbers is 1. Example:
let num1 = 5; // Binary: 0101
let num2 = 3; // Binary: 0011
let result = num1 | num2;
console.log(result); // Output: 7 (Binary: 0111)
Here, the bitwise OR operation sets the bits to 1 if either num1
or num2
has the corresponding bit set to 1.
Bitwise XOR (^) Operation:
The bitwise XOR operation compares each bit of two numbers and returns a new number with bits set to 1 if the corresponding bits of the original numbers are different. Example:
let num1 = 5; // Binary: 0101
let num2 = 3; // Binary: 0011
let result = num1 ^ num2;
console.log(result); // Output: 6 (Binary: 0110)
In this case, the XOR operation sets the bits to 1 where the corresponding bits in num1
and num2
differ.
Bitwise NOT (~) Operation:
The bitwise NOT operation inverts the bits of a number, turning 1s into 0s and vice versa. Example:
let num = 5; // Binary: 0101
let result = ~num;
console.log(result); // Output: -6 (Binary: 1010)
The result is the two’s complement of the binary representation of num
.
Conclusion:
JavaScript’s bitwise operations provide a powerful set of tools for manipulating individual bits in numbers. While they may not be used in everyday coding, understanding their functionality can lead to more efficient and creative solutions in certain scenarios. Incorporating bitwise operations into your programming toolkit can enhance your ability to optimize algorithms and tackle specific challenges with elegance and precision.