DEV Community

Cover image for Bin2Dec converter
Edvinas Pranka
Edvinas Pranka

Posted on

Bin2Dec converter

Today I present my simple project called Bin2Dec. The idea came from Florin Pop app ideas repository, which can be found there florinpop17/app-ideas.

How it works you can see in the animation below. Check the live version too on bin2dec.now.sh

bin2dec converter landing page animation

I implemented it with the Create React App boilerplate. The full source code can be found on my repository epranka/bin2dec.

The following function converts the binary string to a decimal number.

  const calculateDecimal = binaryString => {
    let decimalResult = 0;
    for (
      let i = 0, j = binaryString.length - 1;
      i < binaryString.length;
      i++, j--
    ) {
      const digit = parseInt(binaryString[i]);
      decimalResult += digit * Math.pow(2, j);
    }
    return decimalResult;
  };
Enter fullscreen mode Exit fullscreen mode

Maybe you have the ideas on how to improve it?

Bonus

I created the inverted version of this converter too. It converts the decimal to binary. Check the source code on epranka/dec2bin and live version dec2bin.now.sh

Thanks for reading this. I hope it was interesting to you. Feedback and questions are appreciated.

Follow on Twitter, GitHub, and let’s connect on LinkedIn

Top comments (2)

Collapse
 
ekeijl profile image
Edwin

Reverse the string, so we can start converting bits one by one.
Use Array.reduce to keep track of the sum and each iteration add (current bit * 2index).

const calculateDecimal = binaryString => {
     return [...binaryString].reverse().reduce((sum, bit, i) => sum + (bit * Math.pow(2, i)), 0);
 };
Collapse
 
epranka profile image
Edvinas Pranka

Nice implementation. Just one thing. The app idea challenge was not store the binary value in the array :) I forget to mention it :)