Search code examples
javascriptbinarydecimalletbigint

Getting wrong result for binary to decimal even after using BigInt() in javascript


I am trying to add two given binary strings after converting them to decimals(Numbers) and then converting back the resulting decimal(Number) to string.

I am getting the wrong binary to decimal even after using BigInt().

let a = "10100000100100110110010000010101111011011001101110111111111101000000101111001110001111100001101";
let b="110101001011101110001111100110001010100001101011101010000011011011001011101111001100000011011110011";

var twoSum = function(a, b) {
let a1=BigInt(parseInt(a, 2));
 let b1=BigInt(parseInt(b,2));
let aStr=a1.toString(10);
let bStr=b1.toString(10);

console.log(aStr)
console.log(bStr)
};

console.log(twoSum(a, b));

Output:

        24847893154024981755840167936
        526700554598729745018195542016

Correct result is : 24847893154024981730169397005 & 526700554598729746900966573811

I don't why I am getting the wrong result of binary to decimal.


Solution

  • parseInt returns a Number. Due to Number's limited precision being less than the length of your input strings, you've lost precision at that point. Converting that Number to a BigInt afterwards doesn't bring the lost precision back.

    The solution is to convert the strings to BigInt directly. There was supposed to be a BigInt.parseInt function, but TC39 (the committee that standardizes JavaScript) never got around to finishing that. In the meantime, for non-decimal inputs, the BigInt constructor does understand strings starting with 0x... (hex), 0o... (octal), and 0b... (binary). The latter is what you want in this case. So you could fix your code as follows:

    function parseBinaryToBigInt(a) {
      return BigInt('0b' + a);
    }
    
    function twoSum(a, b) {
      let a1 = parseBinaryToBigInt(a);
      let b1 = parseBinaryToBigInt(b);
      let aStr = a1.toString(10);
      let bStr = b1.toString(10);
    
      console.log(aStr)
      console.log(bStr)
    };