Bitwise Operator(JavaScript)
JavaScript has special operators called bitwise operators. These operators are used for bit-level manipulation of numbers. Bitwise operators are applied to integer values and manipulate integer values as bit representations.
Bitwise operators are used for bit-level operations, setting flags, and certain numeric operations. However, bitwise operators treat numbers as 32-bit signed integers, so one should be aware of the effects of sign bits.
Explanation
& Bitwise AND
The bitwise AND operator returns 1 if both corresponding bits of the operands are 1, otherwise it returns 0.
let a = 5; // Binary: 0101
let b = 3; // Binary: 0011
let result = a & b; // Bitwise AND: 0001 (Result is 1)
console.log(result); // Output: 1
| Bitwise OR
The bitwise OR operator returns 1 if either of the corresponding bits of the operands is 1.
let a = 5; // Binary: 0101
let b = 3; // Binary: 0011
let result = a | b; // Bitwise OR: 0111 (Result is 7)
console.log(result); // Output: 7
^ Bitwise XOR
The bitwise XOR operator returns 1 if the corresponding bits of the operands are different, otherwise it returns 0.
let a = 5; // Binary: 0101
let b = 3; // Binary: 0011
let result = a ^ b; // Bitwise XOR: 0110 (Result is 6)
console.log(result); // Output: 6
~ Bitwise NOT
The bitwise NOT operator flips the bits of its operand. It converts each 1 to 0 and each 0 to 1.
let num = 5; // Binary: 00000000000000000000000000000101
let result = ~num; // Bitwise NOT: 11111111111111111111111111111010 (Result is -6)
console.log(result); // Output: -6
<< Left shift
The left shift operator shifts the bits of a number to the left by a specified number of positions.
let num = 5; // Binary: 00000000000000000000000000000101
let result = num << 2; // Left Shift: 00000000000000000000000000010100 (Result is 20)
console.log(result); // Output: 20
>> Right shift
The right shift operator shifts the bits of a number to the right by a specified number of positions.
let num = 20; // Binary: 00000000000000000000000000010100
let result = num >> 2; // Right Shift: 00000000000000000000000000000101 (Result is 5)
console.log(result); // Output: 5
>>> Unsigned right shift
The unsigned right shift operator shifts the bits of a number to the right by a specified number of positions, filling the leftmost bits with zeros.
let num = -10; // Binary: 11111111111111111111111111110110 (Negative number)
let result = num >>> 2; // Unsigned Right Shift: 00111111111111111111111111111101 (Result is 1073741821)
console.log(result); // Output: 1073741821
---
Discussion
New Comments
No comments yet. Be the first one!