JavaScript Program to Convert a Number to Binary
Last Updated :
27 May, 2024
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:
We will explore all the above methods along with their basic implementation with the help of examples.
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.
Syntax:
function decimalToBinary(decimalNumber) {
return decimalNumber.toString(2);
};
Example: In this example we are using the above-explained approach.
JavaScript
function decimalToBinary(decimalNumber) {
return decimalNumber.toString(2);
}
const decimalNum = 25;
const Result = decimalToBinary(decimalNum);
console.log(Result);
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.
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);
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.
Syntax:
function convertDecimalToBinary(decimalNumber) {
if (decimalNumber === 0) {
//code..
} else {
//code...
}
};
Example: In this example we are using the above-explained approach.
JavaScript
function convertDecimalToBinary(decimalNumber) {
if (decimalNumber === 0) {
// Base case: Return "0" if the number is 0
return "0";
} else {
// Recursive case: Divide the number by 2,
//append the remainder to the result of the recursive call
return convertDecimalToBinary(
Math.floor(decimalNumber / 2)) + (decimalNumber % 2);
}
}
const num1 = 10;
const result = convertDecimalToBinary(num1);
console.log(result);
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.
Example: In this example, we will use the above approach to convert a decimal number to binary.
JavaScript
function decimalToBinary(decimalNumber) {
let binaryArray = [];
while (decimalNumber > 0) {
binaryArray.unshift(decimalNumber % 2);
decimalNumber = Math.floor(decimalNumber / 2);
}
return binaryArray.length ? binaryArray.join('') : '0';
}
const decimalNum = 10;
const result = decimalToBinary(decimalNum);
console.log(result);
Similar Reads
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 i
5 min read
JavaScript Program to Add n Binary Strings
In this article, we are going to learn about Adding n binary strings by using JavaScript. Adding n binary strings in JavaScript refers to the process of performing binary addition on a collection of n binary strings, treating them as binary numbers, and producing the sum in binary representation as
3 min read
JavaScript Program for Binary Representation of Next Number
Given a binary input that represents a binary representation of the positive number n, find a binary representation of n+1. We will try to find out this with the different approaches discussed below. Examples: Input : 10011 Output : 10100 Here n = (19)10 = (10011)2 next greater integer = (20)10 = (1
3 min read
JavaScript Program to Set a Particular Bit in a Number
Setting a specific bit at a given position within a number using JavaScript involves manipulating the binary representation of the number to ensure that a particular bit is turned on set to 1. Examples: Input : n = 10, k = 2Output :14ApproachThe variable "bitPosition" determines the index of the bit
2 min read
JavaScript Program to Add Two Binary Strings
Here are the various ways to add two binary strings Using parseInt() and toString() The parseInt() method used here first converts the strings into the decimal. Ten of these converted decimal values are added together and by using the toString() method, we convert the sum back to the desired binary
4 min read
JavaScript Program to Convert Decimal to Binary Using Recursion
JavaScript allows us to convert decimal numbers to their binary equivalents using recursion, offering two distinct approaches. Through recursive division and concatenation, the first method constructs the binary representation directly. The second method leverages a string and recursion, providing a
2 min read
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 = "11
5 min read
JavaScript Program to Extract the Leftmost Set Bit of a Given Integer
We are given an integer value the task is to extract the leftmost set bit of a given integer in JavaScript. The leftmost set bit is a bit whose value is 1 and is present at the leftmost position in binary representation. The below approaches can be implemented to extract the leftmost set bit. Table
2 min read
JavaScript Program to Check if a Number has Bits in an Alternate Pattern
JavaScript can be used to assess whether a given number follows an alternating pattern in its binary representation. By examining the binary digits of the number, one can determine if the sequence alternates between 0s and 1s, aiding in understanding the binary structure of the input. Examples: Inpu
2 min read
JavaScript Program to Check if all Bits can be made Same by Single Flip
In this article, we will explore how to determine if it's possible to make all bits the same in a binary string by performing a single flip operation. We will cover various approaches to implement this in JavaScript and provide code examples for each approach. Examples: Input: 1101Output: YesExplana
5 min read