If you should ever need to parse a number into an array of bits or a different base you can use the following function:
var splitNumber = (function(MAX) {
for (; MAX + 1 - MAX == 1; MAX *= 2){}
return function (num, radix) {
// Validate num
num = parseInt(num, 10);
if (!isFinite(num) || 0 > num || num > MAX) {
throw new Error('splitNumber() num argument must be a non-negative finite number less than ' + MAX);
}
// Validate radix
radix = parseInt(radix || 10, 10);
if (!(1 < radix && radix <= MAX)) { // Also prevents NaN
throw new Error('splitNumber() radix argument must be greater than 2 and less than ' + MAX);
}
return num.toString(radix).split('');
};
})(1 << 30);
[/code]
Here is an example of the tests and outputs:
I want to thank ildar for contributing the refinement of this function. 😎
4 Comments
ildar · March 14, 2014 at 8:21 AM
[code language=javascript]
var num = 17;
alert(num.toString(2).split('');
alert(num.toString(8).split('');
[/code]
Chris West · March 17, 2014 at 1:44 PM
Good point, that is a much better way to do it. I will update the post shortly. Thanks!
Chris West · March 17, 2014 at 1:57 PM
I guess the only difference is that it will produce an array of strings but that is acceptable. Thanks again.
ildar · March 18, 2014 at 2:19 AM
Take into account that Number.prototype.toString limits the radix within the range 2 through 36. 🙂