我想将二进制字符串转换为数字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)
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
var binary = "1101000";
var digit = parseInt(binary, 2);
console.log(digit);
Run Code Online (Sandbox Code Playgroud)