loading...
Cover image for Bin2Dec converter

Bin2Dec converter

epranka profile image Edvinas Pranka ・1 min read

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;
  };

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

Discussion

pic
Editor guide
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 Author

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