0

i am trying to convert a decimal number into a binary number and i wrote a function in c++ that do this work and it worked fine , but when i wrote the same function in Javascript it didn't work out and printed a false value like "11101111111111" something like that. can anyone tell me what's wrong with this function ?

 var decToBinary=function() {
    var n=16,s="";
    while(n) {
        if(n % 2 == 0)
            s += "0";
        else
            s += "1";
        n /= 2;
    }
    s.reverse();
    return s;
 }
Montaser Qasem
  • 117
  • 2
  • 11
  • Just FYI, there's a built-in function for this. [`toString`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toString): `var n = 16; n.toString(2); // 10000` Also, you have a syntax error in your current code. It should be `var decToBinary = function() { ...` or `function decToBinary() { ...` – Mike Cluck Apr 12 '16 at 16:01
  • i know there's a built in function but what if i want to do it like this , this supposed to work why it didn't ? – Montaser Qasem Apr 12 '16 at 16:07

2 Answers2

0

how do I convert an integer to binary in javascript?

I think this would be the link you'd want to check out.

function dec2bin(dec){
    return (dec >>> 0).toString(2);
}
Community
  • 1
  • 1
hunda27
  • 59
  • 5
  • dude i saw that question and mine is different , read it again please – Montaser Qasem Apr 12 '16 at 16:16
  • Sorry about that, I completely missed that. What you may want to look at is doing s= s.reverse(), since the reverse doesn't actually edit the object. Also, if you look at the string that you get back, it would appear that the correct representation is the inverse of the reserve of "11101111111111". – hunda27 Apr 12 '16 at 16:49
0

The problem stems from the fact that you only terminate when n === 0 but in many cases you'll get n === 1 which will cause it to incrementally divide n by 2 until the limits of floating point math cause it to be zero. Instead, terminate if n is not greater than or equal to 1.

function log(msg) {
  document.querySelector('pre').innerHTML += msg + '\n';
}

function decToBinary(n) {
 var str = '';
 while(n >= 1) {
   if (n % 2 === 0) {
     str += '0';
    } else {
     str += '1';
    }
    
    n /= 2;
  }
  str = str.split('').reverse().join('');
  return str;
}

log('1:  ' + decToBinary(1));
log('2:  ' + decToBinary(2));
log('15: ' + decToBinary(15));
log('16: ' + decToBinary(16));
<pre></pre>
Mike Cluck
  • 31,869
  • 13
  • 80
  • 91