How to convert an integer to binary in JavaScript
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.
js
function toBinary(num) {// does not shift any bits, number stays the same.return numberToBinary >>> 0}
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.
js
function toBinary(num) {return (numberToBinary >>> 0).toString(2)}