Converting large numbers from binary to decimal and back in JavaScript

后端 未结 4 1908
感动是毒
感动是毒 2020-11-29 11:54

I have a very large number represented as binary in JavaScript:

 var largeNumber = \'110100110101101000010100111110100101110111110000100101110001111100111110         


        
4条回答
  •  粉色の甜心
    2020-11-29 12:30

    When you convert it back to binary, you don't parse it as base 2, that's wrong. You're also trying to parse an integer as a float, this can cause imprecision. With this line:

    parseInt(`1.5798770299367407e+199`, 2)
    

    You're telling JS to parse a base 10 as base 2! What you need to do is convert it to binary like so (note the use of parseFloat):

    var largeNumber = '11010011010110100001010011111010010111011111000010010111000111110011111011111000001100000110000011000001100111010100111010101110100010001011010101110011110000011000001100000110000011001001100000110000011000001100000110000111000011100000110000011000001100000110000011000010101100011001110101101001100110100100000110000011000001100000110001001101011110110010001011010001101011010100011001001110001110010100111011011111010000110001110010101010001111010010000101100001000001100001011000011011111000011110001110111110011111111000100011110110101000101100000110000011000001100000110000011010011101010110101101001111101001010010111101011000011101100110010011001001111101';
    
    //intLN is integer of large number
    var intLN = parseFloat(largeNumber, 2); //here, you used base 10 to parse as integer, Incorrect
    console.log(intLN);
    
    var largeNumberConvert = intLN.toString(2); //here, we convert back to binary with toString(radix).
    console.log(largeNumberConvert);

    Before, you converted a decimal to binary. What you need to do is call toString(radix) to convert it back into binary, so:

    var binaryRepresentation = integerFormOfLargeNumber.toString(2);
    

    If you look at the output, you see:

    Infinity
    Infinity
    

    Since your binary number is quite large, it can affect the results. Because JS supports up to 64 bits, the number is way too large. It causes Infinity and is imprecise. If you try re-converting the largeNumberConvert from binary to decimal like this:

    parseInt(largeNumberConvert, 10);
    

    You can see that it outputs Infinity.

提交回复
热议问题