Skip to content

Instantly share code, notes, and snippets.

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