How to use Bitwise Operations In Javascript
In this approach, we utilize bitwise operations to convert a decimal number to its equivalent binary representation. This method is specifically efficient for base 2 conversions. Bitwise operations directly manipulate the bits of a number, making it a fast and efficient method for binary conversion.
Example: In this example, we are performing decimal to binary conversion using bitwise operations.
function decToBaseBitwise(inputNumber, inputBase) {
if (inputBase !== 2) {
return "This method only supports base 2";
}
if (inputNumber === 0) {
return "0";
}
let result = "";
let checkNum = false;
if (inputNumber < 0) {
checkNum = true;
inputNumber = Math.abs(inputNumber);
}
while (inputNumber > 0) {
result = (inputNumber & 1) + result;
inputNumber = inputNumber >> 1;
}
if (checkNum) {
result = "-" + result;
}
return result;
}
let inputNo = 1100;
let inputBase = 2;
let output = decToBaseBitwise(inputNo, inputBase);
console.log(`The Decimal ${inputNo} in base ${inputBase} is: ${output}`);
Output
The Decimal 1100 in base 2 is: 10001001100
JavaScript Program for Decimal to any base conversion
In this JavaScript article, we will see how we can do decimal to any base conversion in JavaScript. The base can not be less than 2 and can not exceed 36, So we always have to find out the base of a decimal that lies in between this range, which is ‘2=< base <=36’.
Example:
Input: number = "1100", base = 2
Output: 10001001100
There are different types of methods to perform decimal to any base conversion in JavaScript:
Table of Content
- Using the ‘toString()’ method in JavaScript
- Using the loop (do-while)
- Using the Array
- Using the Recursion
- Using Bitwise Operations