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
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);
Use the radix parameter of parseInt
:
var binary = "1101000";
var digit = parseInt(binary, 2);
console.log(digit);
parseInt()
with radix is a best solution (as was told by many):
But if you want to implement it without parseInt, here is an implementation:
function bin2dec(num){
return num.split('').reverse().reduce(function(x, y, i){
return (y === '1') ? x + Math.pow(2, i) : x;
}, 0);
}