-1

I do not understande code below which is used to convert decimal number to a binary.

function dec2bin(dec){
  return (dec >>> 0).toString(2);
}

console.log(dec2bin(-5));
VLAZ
  • 26,331
  • 9
  • 49
  • 67
Starlex
  • 11
  • 1
  • A relevant related question: [JavaScript triple greater than](https://stackoverflow.com/questions/7718711/javascript-triple-greater-than) – DBS May 25 '22 at 09:48

2 Answers2

0

dec >>> 0 is an unsigned 32-bit right-shift of zero.

This has the effect of

a) truncating the non-integer part of the number

b) converting the number to 32-bit

c) removing the sign bit from the 32-bit number

someNumber.toString(2)

will convert to a string representation of the binary value of someNumber.

spender
  • 117,338
  • 33
  • 229
  • 351
  • Thank you for your clarification, I have understood the process, but I still do not know how (( >>> Zero fill right shift )) works with zero, like what is the result of ( -7 >>> 0 ) and (7 >>> 0 ) ? – Starlex May 25 '22 at 13:06
0

function dismailToBinary(num) {
  let binary = "";
  while (num > 0) {
    let digit = num % 2;
    binary = "" + digit + binary;
    num = parseInt(num / 2);
  }
  return binary;
}
console.log(dismailToBinary(5));

function decimalToBinary(num) {
  let binary = "";
  while (num > 0) {
    let digit = num % 2;
    binary = "" + digit + binary;
    num = parseInt(num / 2);
  }
  return binary;
}
console.log(decimalToBinary(5));