Skip to main content
2 of 3
added 100 characters in body
ganesh phirke
  • 473
  • 1
  • 3
  • 12

we can also calculate the binary for positive or negative numbers as below:

function toBinary(n){
    let binary = "";
    if (n < 0) {
      n = 0xFFFFFFFF + n + 1;
    }
    while(Math.ceil(n/2) > 0){
        binary = n%2 + binary;
        n = Math.floor(n/2);
    }
    return binary;
}

console.log(toBinary(7));
console.log(toBinary(-7));

ganesh phirke
  • 473
  • 1
  • 3
  • 12