Negative numbers to binary string in JavaScript

前端 未结 5 1434
无人及你
无人及你 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:22

    var binary = (-3 >>> 0).toString(2); // coerced to uint32
    
    console.log(binary);
    
    console.log(parseInt(binary, 2) >> 0); // to int32
    

    on jsfiddle

    output is

    11111111111111111111111111111101
    -3 
    

提交回复
热议问题