Negative numbers to binary string in JavaScript

前端 未结 5 1428
无人及你
无人及你 2020-11-30 22:15

Anyone knows why javascript Number.toString function does not represents negative numbers correctly?

//If you try
(-3).toString(2); //shows \"-11\"
// but if         


        
5条回答
  •  攒了一身酷
    2020-11-30 22:37

    Just to summarize a few points here, if the other answers are a little confusing:

    • what we want to obtain is the string representation of a negative number in binary representation; this means the string should show a signed binary number (using 2's complement)
    • the expression (-3 >>> 0).toString(2), let's call it A, does the job; but we want to know why and how it works
    • had we used var 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 want
    • expression A works like this:

    1) (-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."

提交回复
热议问题