how to convert binary string to decimal?


Question

I want to convert binary string in to digit E.g

var binary = "1101000" // code for 104
var digit = binary.toString(10); // Convert String or Digit (But it does not work !)
console.log(digit);

How is it possible? Thanks

1
68
4/21/2012 12:18:35 PM

Accepted Answer

The parseInt function converts strings to numbers, and it takes a second argument specifying the base in which the string representation is:

var digit = parseInt(binary, 2);

See it in action.

137
4/21/2012 12:20:20 PM

ES6 supports binary numeric literals for integers, so if the binary string is immutable, as in the example code in the question, one could just type it in as it is with the prefix 0b or 0B:

var binary = 0b1101000; // code for 104
console.log(binary); // prints 104

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon