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
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.
Top comments (2)
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).Nice implementation. Just one thing. The app idea challenge was not store the binary value in the array :) I forget to mention it :)