Anyone knows why javascript Number.toString function does not represents negative numbers correctly?
//If you try
(-3).toString(2); //shows \"-11\"
// but if
Just to summarize a few points here, if the other answers are a little confusing:
(-3 >>> 0).toString(2)
, let's call it A, does the job; but we want to know why and how it worksvar num = -3; num.toString(-3)
we would have gotten -11
, which is simply the unsigned binary representation of the number 3 with a negative sign in front, which is not what we want1) (-3 >>> 0)
The >>>
operation takes the left operand (-3), which is a signed integer, and simply shifts the bits 0 positions to the left (so the bits are unchanged), and the unsigned number corresponding to these unchanged bits.
The bit sequence of the signed number -3 is the same bit sequence as the unsigned number 4294967293, which is what node gives us if we simply type -3 >>> 0
into the REPL.
2) (-3 >>> 0).toString
Now, if we call toString
on this unsigned number, we will just get the string representation of the bits of the number, which is the same sequence of bits as -3.
What we effectively did was say "hey toString, you have normal behavior when I tell you to print out the bits of an unsigned integer, so since I want to print out a signed integer, I'll just convert it to an unsigned integer, and you print the bits out for me."