How to use Bitwise operation In Javascript
Create a function and initialize a variable decimal with value 0. Now determine the length of binary string binary. Now we Iterate through the binary digits of the input string from left to right. If the current digit is ‘1’, perform a left shift operation by (n – i – 1) positions, where n is the length of the binary string, and bitwise OR with the current value of decimal. It return decimal.
Example: Demonstration of converting of binary to decimal using Bitwise operation
function binaryToDecimalBitwise(binary) {
let decimal = 0;
const n = binary.length;
for (let i = 0; i < n; i++) {
if (binary[i] === "1") {
decimal |= 1 << (n - i - 1);
}
}
return decimal;
}
const binaryNumber = "10000";
console.log("Result is : ",
binaryToDecimalBitwise(binaryNumber));
Output
Result is : 16
Time Complexity: O(n)
Space Complexity: O(1)
How to convert binary to decimal in JavaScript?
A binary number is a number expressed in the binary numeral system, which uses only two symbols 0 and 1. Decimal numbers are base 10 in a JavaScript number system that uses 10 digits from 0 to 9. We are given a number as Binary input we have to convert it into decimal in JavaScript and print the result.
Contact Us