Last active
August 29, 2015 14:07
-
-
Save Karlina-Bytes/e6d8d3957ab2881d4068 to your computer and use it in GitHub Desktop.
A JavaScript function for converting a number from binary to decimal.
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
/********************************************************* | |
* Converts a positive integer from binary to decimal. | |
* @param {Number} binaryNumber (e.g. 1101) | |
* @return {Number} decimalNumber (e.g. 13) | |
********************************************************/ | |
function binaryToDecimal( binaryNumber ) { | |
// decimalNumber represents a summation of digit values. | |
var decimalNumber = 0; | |
// placeValue represents a power of two. | |
var placeValue = 1; | |
// Compute each digit value (from right to left). | |
while ( binaryNumber > 0 ) { | |
// Divide binaryNumber by 10. Store the decimal remainder. | |
var remainder = binaryNumber % 10; | |
// Determine the remainder digit. | |
var digitValue = remainder * placeValue; | |
// Add the digitValue to the decimalNumber sum. | |
decimalNumber = decimalNumber + digitValue; | |
// Increment the placeValue | |
placeValue *= 2; | |
// Increment to the next digit (left adjacent). | |
binaryNumber = Math.floor( binaryNumber / 10 ); | |
} | |
// Return the sum of digit values. | |
return decimalNumber; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment