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>
2 Answers 2
A general feeling after taking a glance at your code is that you do this:
if (decimalNumber > 0) ret.push(decimalNumber);
i.e. that you put in the same line of code, both the if statement and the if body.
I would expect to see (with brackets maybe):
if (decimalNumber > 0)
ret.push(decimalNumber);
That might be of course a personal taste, but I thought it would be nice for you to think twice about it.
Also:
// Local variables
var ret = [];
var bit = decimalNumber % 2;
everybody knows that ret
and bit
are local variables, so, think twice2 for removing that comment.
-
\$\begingroup\$ Had the feeling that I need some kind of separator when opening another "section" after the parameter-checks. But yes you are right. It's a bit stupid within there. \$\endgroup\$michael.zech– michael.zech2016年03月09日 12:46:37 +00:00Commented Mar 9, 2016 at 12:46
Comment says, that function will return a string, and then returns a number.
if (decimalNumber === 0) return 0
Best improvement would be using a native method
function getBinaryNumber(num, sep) {
if (typeof num != "number") num = parseFloat(num)
return sep ? num.toString(2).split("").join(sep) : num.toString(2)
}
I would remove separator parameter, as it makes no sense to combine this functionality.
function getBinaryNumber(num) {
return (typeof num == "number" ? num : parseFloat(num)).toString(2)
}
-
\$\begingroup\$ Thanks a lot. You've given me lots of useful hints. :) But concerning the isNaN-check you are wrong. It shall intercept the case: Something which can't be converted to a number (e.g. 'a#bc') has been given as parameter. Without that check 'bit' gets the value NaN after applying the mod-operator the first time. This would become the return value later. \$\endgroup\$michael.zech– michael.zech2016年03月10日 07:31:20 +00:00Commented Mar 10, 2016 at 7:31
-
\$\begingroup\$ My bad about isNaN, removed this from answer \$\endgroup\$Lauri– Lauri2016年03月10日 11:12:37 +00:00Commented Mar 10, 2016 at 11:12
Explore related questions
See similar questions with these tags.
base_convert
. You would need less code in comparison with js. php.net/manual/en/function.base-convert.php \$\endgroup\$