Anyone knows why javascript Number.toString
function does not represents negative numbers correctly?
//If you try
(-3).toString(2); //shows "-11"
// but if you fake a bit shift operation it works as expected
(-3 >>> 0).toString(2); // print "11111111111111111111111111111101"
I am really curious why it doesn't work properly or what is the reason it works this way? I've searched it but didn't find anything that helps.
on jsfiddle
output is
-3 >>> 0 (right logical shift) coerces its arguments to unsigned integers, which is why you get the 32-bit two's complement representation of -3.
http://en.wikipedia.org/wiki/Two%27s_complement
http://en.wikipedia.org/wiki/Logical_shift
Short answer:
The
toString()
function basically takes the decimal, converts it to binary and adds a "-" sign.A zero fill right shift converts it's operand to a 32 signed bit integer in two complements format.
A more detailed answer:
Question 1:
It's in the function
.toString()
. When you output a number via.toString()
:So basically it takes the decimal, converts it to binary and adds a "-" sign.
Question 2:
A zero fill right shift converts it's operand to a 32 signed bit integer.