Bit Manipulation Method

Bit manipulation is a technique where you manipulate individual bits of a number using bitwise operators. In the context of converting to binary, you can repeatedly extract the least significant bit (LSB) of the decimal number while shifting the number to the right.

Syntax:

for (; decimalNumber > 0;
decimalNumber = Math.floor(decimalNumber / 2)) {
binary = (decimalNumber % 2) + binary;
}

Example: In this example, The function decimalToBinary converts a decimal number to binary using a for loop. Bitwise operations shift the number’s bits, constructing the binary representation.

Javascript
function decimalToBinary(decimalNumber) {
    let binary = "";
    for (; decimalNumber > 0; decimalNumber >>= 1) {
        binary = (decimalNumber & 1) + binary;
    }
    return binary || "0";
}

const num1 = 32;
const Result = decimalToBinary(num1);
console.log(Result); 

Output
100000

JavaScript Program to Convert a Number to Binary

We are going to learn the conversion of a number to binary by using JavaScript, Convert a number to binary in JavaScript refers to the process of converting a decimal number into its binary representation, which uses only the digits 0 and 1 to represent the value

Converting a number to binary in JavaScript involves transforming a decimal (base 10) number into its binary (base 2) representation.

For example:

(25)10 = (11001)2
(32)10= (100000)2
(8)10= (1000)2

There are several methods that can be used to Convert a number to binary in JavaScript, which are listed below:

Table of Content

  • Approach 1: Using toString() method
  • Approach 2: Bit Manipulation Method
  • Approach 3: Recursive Method
  • Approach 4: Using Array-Based Method

We will explore all the above methods along with their basic implementation with the help of examples.

Similar Reads

Approach 1: Using toString() method

The built-in toString() method in JavaScript allows you to convert a number to a string representation in a given base. By providing a base of 2, you can convert a decimal number to its binary representation....

Approach 2: Bit Manipulation Method

Bit manipulation is a technique where you manipulate individual bits of a number using bitwise operators. In the context of converting to binary, you can repeatedly extract the least significant bit (LSB) of the decimal number while shifting the number to the right....

Approach 3: Recursive Method

The recursive method for converting a number to binary involves repeatedly dividing the number by 2 and appending remainders to the binary representation using a recursive function....

Approach 4: Using Array-Based Method

In this method, we use an array to collect the binary digits (bits) as we repeatedly divide the decimal number by 2. Once we have collected all the bits, we join them into a string to form the binary representation....