Vivek Kumar Shukla
Vivek Kumar Shukla

Reputation: 196

Binary to Decimal conversion showing wrong result for large number in JavaScript

I am trying to convert below binary(64 bit) number to decimal number '1000000010000001000011111111100100010110011001011001110111000111'

but it is showing the wrong result. I am using below function to convert the number.

binaryToDecimal(binaryVal) {
    let val = 0,
      finalVal = 0,
      binaryArray = binaryVal.split('');

    for (let index = 0; index < binaryArray.length; index++) {
      if(Number(binaryArray[index])){
        val = Math.pow(2, binaryArray.length - (index + 1));
      }
      finalVal = finalVal + val;
      val = 0;
    }
    return finalVal;
  }

The value I am getting: 9259699871347483000 the correct result will be: 9259699871347482055

please suggest if it is possible in JavaScript.

Thanks in advance.

Upvotes: 4

Views: 490

Answers (2)

Nina Scholz
Nina Scholz

Reputation: 386838

You could take BigInt for reducing.

var factor = BigInt(2),
    binary = '1000000010000001000011111111100100010110011001011001110111000111',
    decimal = Array
        .from(binary, BigInt)
        .reduce((r, b) => r * factor + b, BigInt(0));
    

console.log(decimal.toString());

Upvotes: 3

Ilijanovic
Ilijanovic

Reputation: 14914

Here a very compact solution to your problem just add 0b infront of your number and then return as a BigInt

function binaryToDecimal(binaryVal) {
   return BigInt(`0b${binaryVal}`)
}

Upvotes: 3

Related Questions