why does this binary conversion give me an incorrect value in javascript?

0

I have the following decimal number converter

function binario(numero) { 

  var division = 0; 
  var binario = []; 
  do { 
    division = numero / 2; 
    if (numero % 2 == 0) { 
      binario.unshift("1"); 
    } else { 
      binario.unshift("0"); 
    } 
    numero = Math.round(division); 
  } while (numero > 1); 
  binariof = binario.join(""); 
  alert(binariof); 

} 
binario(28);

The problem: the conversion returns me wrong, in this case 28 would be 11100 and returns 11011.

What am I doing wrong?

    
asked by Victor Alvarado 06.05.2017 в 15:32
source

1 answer

3

You have your logic wrong:

  • When the remainder is 0 in the division, that is the number you must add to your array, not 1.
  • Then you must round down the nearest integer after dividing, not up, then change round to floor
  • Finally you must also divide by 1, that number you can not skip.
  • I'll leave the Snippet for you to check:

    function binario(numero){ 
        var division=0; 
        var binario=[]; 
        
        do { 
            division=numero/2; 
            if (numero%2==0) { 
                binario.unshift("0"); 
            } 
            else { 
                binario.unshift("1"); 
            } 
            numero=Math.floor(division); 
            }
            while(numero >= 1); 
            binariof=binario.join(""); 
            alert(binariof);     
        } 
    binario(28);

    Greetings and luck

        
    answered by 06.05.2017 / 15:50
    source