How to useBitwise Operations and an Array in Javascript
This approach involves using bitwise operations to convert a decimal number to binary. The idea is to repeatedly use the bitwise AND operator with 1 to extract the least significant bit of the number and then use the right shift operator to shift the bits to the right.
Example: In this example The function decimalToBinary converts a decimal number to binary using bitwise operations, pushing remainders to an array, then reverses and joins it to get the binary representation.
function decimalToBinary(N) {
if (N === 0) return "0";
let binaryArray = [];
while (N > 0) {
binaryArray.push(N & 1);
N = N >> 1;
}
return binaryArray.reverse().join('');
}
let number = 10;
let binary = decimalToBinary(number);
console.log("The binary representation of the given number is: " + binary);
Output
The binary representation of the given number is: 1010
JavaScript Program to Convert Decimal to Binary
In this article, we are going to learn the conversion of numeric values from decimal to binary. Binary is a number system with 2 digits (0 and 1) representing all numeric values.
Given a number N which is in decimal representation. our task is to convert the decimal representation of the number to its equivalent binary representation.
Example 1:
Input : 7
Output : 111
Input : 10
Output : 1010
If the decimal number is 10.
- The remainder when 10 is divided by 2 is zero. Therefore, arr[0] = 0.
- Divide 10 by 2. The new number is 10/2 = 5.
- The remainder when 5 is divided by 2 is 1. Therefore, arr[1] = 1.
- Divide 5 by 2. The new number is 5/2 = 2.
- The remainder, when 2 is divided by 2, is zero. Therefore, arr[2] = 0.
- Divide 2 by 2. The new number is 2/2 = 1.
- The remainder when 1 is divided by 2 is 1. Therefore, arr[3] = 1.
- Divide 1 by 2. The new number is 1/2 = 0.
- Since the number becomes = 0.
- Print the array in reverse order. Therefore the equivalent binary number is 1010.
There are several approaches that can be used to Convert Decimal to Binary, which are listed below:
Table of Content
- Using unsigned right shift operator (>>>)
- Using Loop and String Concatenation
- Using toString(2) Method
- Using Array and Math method
- Using Bitwise Operations and an Array
We will explore all the above methods along with their basic implementation with the help of examples.