Sometimes we have to play with binaries to get quick and fast results. Let’s see how can we convert one.

Unsigned right shift (>>>)

In order to work also with negative numbers, we use the Unsigned right shift operator first to convert it to the non-negative integer.

1
2
3
function toBinary(num) {
return numberToBinary >>> 0; // does not shift any bits, number stays the same.
}

We are not done yet!

ToString to the rescue

We still need to convert it to the binaries. We can do that by simply making use of the ToString method.

1
2
3
function toBinary(num) {
return (numberToBinary >>> 0).toString(2);
}