I wrote a simple function to turn a number that is in base 10 into a binary number. I've looked up this how to do this on this website and I haven't understood a good deal of it. I'm sure the function I've written is very strange but it seems to do the trick.
Here is a jsfiddle showing it in action: http://ift.tt/2sxs94u
And here is the function code:
var toBinary = function(x) {
x = parseInt(x);
if (x < 0) {
var k = '-'
x = Math.sqrt(Math.pow(x, 2));
}
if (x == 0) {
return 0;
}
var y = x;
var g = [];
while (Math.log2(y) >= 0) {
var n = parseInt(Math.log2(y));
g.push(n+1);
y = y - Math.pow(2, n);
}
var binArray = [];
for (var i = 0; i < g[0]; i++) {
binArray.push(0);
}
for (var i = 0; i < g.length; i++) {
binArray[binArray.length-g[i]] = 1;
}
var binary = binArray.join("");
return (k || "") + binary;
};
I don't have a lot of tools yet for evaluating this so my question is as follows:
What this function returns looks right, but how can I make sure what I'm getting is actually a binary number and not just a string that looks like a binary number. Am I missing a few key pieces? Or is my approach a dead end?
An additional question: Is there a built-in function in JS to do this for me? Mostly, this is a learning exercise for me so I'm still interested in producing a base10 to base2 number converting function.
Aucun commentaire:
Enregistrer un commentaire