Handling Floating-Point Arithmetic in JavaScript: A Simple Approach

Don’t we all love Javascript?

I ❤ Js
Converting a binary number to a decimal number is a common task in programming. In JavaScript, this can be done easily using built-in functions or by writing a custom function to convert a binary string to a decimal. Understanding how binary to decimal conversion works is essential for working with different number systems.

In this article, we’ll explore how to convert binary to decimal in JavaScript using multiple approaches. By the end, you’ll be able to convert binary strings to decimal numbers and vice versa, ensuring that you understand how number conversion works in JavaScript.

What is a Binary Number?


A binary number is a number expressed in the binary system, which uses only two digits: 0 and 1. Each digit in a binary string represents an increasing power of 2, starting from the rightmost digit (which represents 2^0) and moving leftward.

For example, the binary number 1011 can be converted to decimal as follows:

1 * 2^3 + 0 * 2^2 + 1 * 2^1 + 1 * 2^0 = 8 + 0 + 2 + 1 = 11

How to Convert Binary to Decimal

In JavaScript, converting a binary string to a decimal number can be done using the parseInt() function, or you can write your own function to convert the binary to decimal using bitwise operations.

Approach 1: Using parseInt() Function

The easiest way to convert a binary number to a decimal number in JavaScript is by using the built-in parseInt() function. This function takes two arguments: the binary string and the base (in this case, 2 for binary).

Here’s how to do it:

function binaryToDecimal(binaryString) {
    return parseInt(binaryString, 2);
}

const binaryNumber = "1011";
const decimalNumber = binaryToDecimal(binaryNumber);
console.log(`The decimal value of the binary string ${binaryNumber} is ${decimalNumber}`);

Explanation:

  • parseInt(binaryString, 2): This converts the binary string to a decimal number. The second argument (2) specifies the base of the input number (binary).
  • The binary string "1011" is converted to the decimal number 11.

Approach 2: Writing a Custom Function

If you want to better understand how binary to decimal conversion works, you can write a custom function that manually converts a binary string to a decimal number.

function customBinaryToDecimal(binaryString) {
    let decimal = 0;
    for (let i = 0; i < binaryString.length; i++) {
        const bit = binaryString[binaryString.length - 1 - i]; // Get the bit from the end
        decimal += bit * Math.pow(2, i); // Add the corresponding power of 2
    }
    return decimal;
}

const binaryString = "1101";
const decimalResult = customBinaryToDecimal(binaryString);
console.log(`The decimal conversion of binary ${binaryString} is ${decimalResult}`);

Explanation:

  • We iterate through the binary string from right to left.
  • For each bit, we multiply it by 2 raised to the position of the bit.
  • Finally, we sum all these values to get the decimal number.

For example, for the binary string "1101", this is what happens in the function:

1 * 2^3 + 1 * 2^2 + 0 * 2^1 + 1 * 2^0 = 8 + 4 + 0 + 1 = 13

Approach 3: Using Bitwise Shift Operators

Another approach is to use bitwise shift operators to manually convert binary to decimal. This method involves shifting bits to the left and adding the current bit's value.

function bitwiseBinaryToDecimal(binaryString) {
    let decimal = 0;
    for (let i = 0; i < binaryString.length; i++) {
        decimal = (decimal << 1) | (binaryString[i] - '0');
    }
    return decimal;
}

const binaryValue = "1010";
const decimalValue = bitwiseBinaryToDecimal(binaryValue);
console.log(`The decimal of binary ${binaryValue} is ${decimalValue}`);

Explanation:

  • decimal << 1: This left shifts the current decimal value by 1, which is equivalent to multiplying it by 2.
  • |: The bitwise OR adds the current bit’s value to the decimal.

This method is often faster in certain environments where performance optimization is crucial, but it might be harder to understand for beginners.

Converting Decimal to Binary


Now that we’ve covered how to convert binary to decimal, let’s take a quick look at how to convert a decimal numberto a binary string.

Approach 1: Using toString()

In JavaScript, you can use the toString() method to convert a decimal number to a binary string.

function decimalToBinary(decimalNumber) {
    return decimalNumber.toString(2);
}

const decimalNum = 13;
const binaryString = decimalToBinary(decimalNum);
console.log(`The binary representation of ${decimalNum} is ${binaryString}`);

Approach 2: Writing a Custom Decimal to Binary Function

You can also write your own function to convert a decimal number to a binary string:

function customDecimalToBinary(decimalNumber) {
    let binary = "";
    while (decimalNumber > 0) {
        binary = (decimalNumber % 2) + binary;
        decimalNumber = Math.floor(decimalNumber / 2);
    }
    return binary || "0"; // Return "0" if the decimal number is 0
}

const decimalVal = 9;
const binaryResult = customDecimalToBinary(decimalVal);
console.log(`The binary string of ${decimalVal} is ${binaryResult}`);

Explanation:

  • We divide the decimal number by 2 repeatedly.
  • For each division, we take the remainder and prepend it to the binary string.
  • The process continues until the decimal number becomes 0.

For example, converting 9 to binary gives:

sql
9 / 2 = 4 remainder 1 (binary digit)
4 / 2 = 2 remainder 0 (binary digit)
2 / 2 = 1 remainder 0 (binary digit)
1 / 2 = 0 remainder 1 (binary digit)

Result: 1001

Conclusion


Converting binary to decimal and decimal to binary in JavaScript is straightforward once you understand the underlying principles. Whether you use the built-in parseInt() method for binary to decimal conversion or create your own custom conversion function, the process is relatively simple.

  • Binary to decimal conversion can be done using JavaScript’s parseInt(), custom functions, or bitwise operators.
  • Decimal to binary conversion can be achieved with the toString() method or a custom loop-based approach.

By mastering these techniques, you can confidently handle number conversions in JavaScript for a wide range of use cases.

FAQs


1. How do you convert a binary number to a decimal number in JavaScript?
You can convert a binary number to a decimal number using parseInt(binaryString, 2), where the second argument specifies that the input is in binary.

2. What is a binary string?
A binary string is a string of numbers composed of only 0s and 1s, representing a number in the binary system.

3. How do you convert a decimal number to binary in JavaScript?
You can convert a decimal number to a binary string using decimalNumber.toString(2) or by writing a custom loop that performs successive divisions by 2.

4. Why does JavaScript use base 2 for binary conversion?
Base 2 is used in binary because it represents numbers using only two digits: 0 and 1, which are the foundation of binary arithmetic in computer systems.

5. Can bitwise operations be used to convert binary to decimal?
Yes, bitwise shift operators can be used to convert binary to decimal by shifting bits and adding their values based on powers of 2.

6. What is the difference between binary and decimal number systems?
The binary system uses only two digits (0 and 1), while the decimal system uses ten digits (0-9). Binary is commonly used in computers, while decimal is used in everyday mathematics.

By understanding these concepts, you’ll be well-equipped to handle number conversions in your JavaScript projects with ease.



Like 187 likes
Tino Thamjarat
Share:

Join the conversation

This will be shown public
All comments are moderated

Get our stories delivered

From us to your inbox weekly.