如何将二进制字符串转换为十进制?

70 javascript node.js

我想将二进制字符串转换为数字Eg

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

这怎么可能?谢谢

Jon*_*Jon 143

parseInt函数将字符串转换为数字,它采用第二个参数指定字符串表示形式的基数:

var digit = parseInt(binary, 2);
Run Code Online (Sandbox Code Playgroud)

看到它在行动.

  • @srph:这并不奇怪,基数2中的101在基数10中是5. (9认同)
  • 知道了 我一定误会了`parseInt`。我以为它将以10为基数的字符串转换为字符串->任何(想像`parseInt('5612',2)`都将返回其二进制形式;)。 (2认同)

Md *_*iar 28

var num = 10;

alert("Binary " + num.toString(2));   // 1010
alert("Octal " + num.toString(8));    // 12
alert("Hex " + num.toString(16));     // a

alert("Binary to Decimal " + parseInt("1010", 2));  // 10
alert("Octal to Decimal " + parseInt("12", 8));     // 10
alert("Hex to Decimal " + parseInt("a", 16));       // 10
Run Code Online (Sandbox Code Playgroud)


GOT*_*O 0 12

ES6支持整数的二进制数字文字,因此如果二进制字符串是不可变的,就像问题中的示例代码一样,可以只使用前缀0b或者输入0B:

var binary = 0b1101000; // code for 104
console.log(binary); // prints 104
Run Code Online (Sandbox Code Playgroud)


Sal*_*ali 11

parseInt() 使用基数是最好的解决方案(正如许多人所说):

但是如果你想在没有parseInt的情况下实现它,这里有一个实现:

  function bin2dec(num){
    return num.split('').reverse().reduce(function(x, y, i){
      return (y === '1') ? x + Math.pow(2, i) : x;
    }, 0);
  }
Run Code Online (Sandbox Code Playgroud)


phi*_*hag 10

使用radix参数parseInt:

var binary = "1101000";
var digit = parseInt(binary, 2);
console.log(digit);
Run Code Online (Sandbox Code Playgroud)