I made this decimal to binary conversion as an exercise for myself and because it is obviously often asked during job interviews / tests.
Any hints concerning possible improvements welcomed.
// -- START : Testing the function --------
var display = document.querySelector('div');
var result = '';
var n = 255;
var maxSpace = n.toString().length;
// Assigning wrong parameter.
console.log('Result empty: ' + getBinaryNumber());
console.log('Result string: ' + getBinaryNumber('abc'));
// Helper function: Avoiding "stairs".
function getSpaces(count, someChar) {
if (!count) return '';
var ret = '';
for (var i = 0; i < count; i++) {
ret += someChar;
}
return ret;
}
var spaces = getSpaces(maxSpace, '0');
for (var i = 0; i <= n; i++) {
result +=
(spaces + i).slice(- maxSpace) +
' : ' + getBinaryNumber(i, ' ') + '<br />';
}
display.innerHTML = result;
// -- END : Testing the function --------
// Converts a decimal number to a binary number.
// -- Parameter --------------------------
// Number - The decimal number to convert.
// -- Return -----------------------------
// String - The number in it's binary
// represention.
// On error:
// Returns an empty string.
function getBinaryNumber (decimalNumber, separator) {
// Parameter check
if (decimalNumber === 0) return 0;
if (!decimalNumber) return '';
if (isNaN(decimalNumber)) return '';
separator = separator || '';
// Local variables
var ret = [];
var bit = decimalNumber % 2;
ret.push(bit);
decimalNumber = ~~(decimalNumber / 2);
while (decimalNumber > 1) {
bit = decimalNumber % 2;
ret.push(bit);
decimalNumber = ~~(decimalNumber / 2);
}
if (decimalNumber > 0) ret.push(decimalNumber);
return ret.reverse().join(separator);
}
<div></div>
base_convert
. You would need less code in comparison with js. php.net/manual/en/function.base-convert.php \$\endgroup\$