Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

251
Views
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.

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

let a = "10100000100100110110010000010101111011011001101110111111111101000000101111001110001111100001101";
// Binary to decimal
const d = BigInt('0b' + a);
// Turn the binary
const b = BigInt(a);


about 4 years ago · Juan Pablo Isaza Report

0

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)
};
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!