Created
August 28, 2021 00:32
-
-
Save Blazing-Mike/2cc9fb131c1924a116ece439b1e37026 to your computer and use it in GitHub Desktop.
Convert Binary to decimal with javascript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// METHOD 1 (IN-BUILT FUNCTION) | |
function convertBaseToBinary(bin) { | |
return parseInt(bin, 2).toString(10); // Convert arguments from one radix/base to radix in toString()/ | |
} | |
// USING FOR LOOP & parseInt FUNCTION | |
function bin2dec(bin) { | |
var decimal = 0; | |
for (var index = bin.length - 1; index >= 0; index--) { | |
decimal += parseInt(bin[index]) * Math.pow(2, bin.length - 1 - index); | |
return decimal; | |
} | |
} | |
console.log(bin2dec('101')); | |
console.log(convertBaseToBinary('101')); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment