How To Convert Binary Numbers To Decimal In Javascript | letsbug.com
Hi everyone in this article we going to make a function to convert binary numbers into decimal numbers.
So before that make sure you are know how to convert the binary numbers to decimal on papers in traditional way. And over here we are just going to implement that logic into code.
And the language is javascript but the logic can be implemented in any language you want. And we are using node.js as javascript runtime.
Binary to Decimal In Javascript
code:
const toDecimal = (binaryNumber) => {const digits = String(binaryNumber).split("").reverse()let sum = 0let counter = 1digits.forEach(e => {if(Number(e) !== 0) sum = sum + countercounter = counter * 2})return sum}console.log(toDecimal(0))console.log(toDecimal(10))console.log(toDecimal(11010))console.log(toDecimal(1001))console.log(toDecimal(101))
output:
$ node index.js
0
2
26
9
5
Thankyou :)
Comments
Post a Comment