我想将二进制字符串转换为数字 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);
怎么可能? 感谢
答案 0 :(得分:133)
parseInt
函数将字符串转换为数字,它接受第二个参数,指定字符串表示形式所在的基数:
var digit = parseInt(binary, 2);
<强> See it in action 强>
答案 1 :(得分:12)
ES6支持整数的binary numeric literals,因此如果二进制字符串是不可变的,就像问题中的示例代码一样,可以只使用前缀0b
或{{ 1}}:
0B
答案 2 :(得分:10)
答案 3 :(得分:10)
parseInt()
是最好的解决方案(正如许多人所说):
但是如果你想在没有parseInt的情况下实现它,这里有一个实现:
function bin2dec(num){
return num.split('').reverse().reduce(function(x, y, i){
return (y === '1') ? x + Math.pow(2, i) : x;
}, 0);
}
答案 4 :(得分:3)
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
答案 5 :(得分:2)
function binaryToDecimal(string) {
let decimal = +0;
let bits = +1;
for(let i = 0; i < string.length; i++) {
let currNum = +(string[string.length - i - 1]);
if(currNum === 1) {
decimal += bits;
}
bits *= 2;
}
console.log(decimal);
}
答案 6 :(得分:1)
仅用于功能性JS练习的另一个实现可能是
var bin2int = s => Array.prototype.reduce.call(s, (p,c) => p*2 + +c)
console.log(bin2int("101010"));
+c
强制String
输入c
到Number
类型值以便正确添加。
答案 7 :(得分:0)
我收集了所有其他建议,并创建了以下函数,该函数具有3个参数:数字和该数字来自的基数以及该数字将要基于的基数:
changeBase(1101000, 2, 10) => 104
运行代码段以自行尝试:
function changeBase(number, fromBase, toBase) {
if (fromBase == 10)
return (parseInt(number)).toString(toBase)
else if (toBase == 10)
return parseInt(number, fromBase);
else{
var numberInDecimal = parseInt(number, fromBase);
return (parseInt(numberInDecimal)).toString(toBase);
}
}
$("#btnConvert").click(function(){
var number = $("#txtNumber").val(),
fromBase = $("#txtFromBase").val(),
toBase = $("#txtToBase").val();
$("#lblResult").text(changeBase(number, fromBase, toBase));
});
#lblResult{
padding: 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="txtNumber" type="text" placeholder="Number" />
<input id="txtFromBase" type="text" placeholder="From Base" />
<input id="txtToBase" type="text" placeholder="To Base" />
<input id="btnConvert" type="button" value="Convert" />
<span id="lblResult"></span>
<p>Hint: <br />
Try 110, 2, 10 and it will return 6; (110)<sub>2</sub> = 6<br />
or 2d, 16, 10 => 45 meaning: (2d)<sub>16</sub> = 45<br />
or 45, 10, 16 => 2d meaning: 45 = (2d)<sub>16</sub><br />
or 2d, 2, 16 => 2d meaning: (101101)<sub>2</sub> = (2d)<sub>16</sub><br />
</p>
仅供参考:如果您想将2d作为十六进制数字传递,则需要将其作为字符串发送,如下所示:
changeBase('2d', 16, 10)
答案 8 :(得分:0)
使用一些更多的ES6语法和自动功能对常规二进制转换算法进行了轻微修改:
// Step 1: Convert binary sequence string to Array (assuming it wasnt already passed as array)
// Step 2: Reverse sequence to force 0 index to start at right-most binary digit as binary is calculated right-left
// Step 3: 'reduce' Array function traverses array, performing summation of (2^index) per binary digit [only if binary digit === 1] (0 digit always yields 0)
// n
// NOTE: Binary conversion formula - ∑ (d * 2^i) {where d=binary digit, i=array index, n=array length-1 (starting from right)}
// i=0
let decimal = Array.from(binaryString).reverse().reduce((total, val, index)=>val==="1"?total + 2**index:total, 0);
console.log(`Converted BINARY sequence (${binaryString}) to DECIMAL (${decimal}).`);