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

我想把二进制字符串转换成数字 例如

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

这怎么可能? 谢谢

189503 次浏览

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

var digit = parseInt(binary, 2);

看到它的行动。

使用 parseInt基数参数:

var binary = "1101000";
var digit = parseInt(binary, 2);
console.log(digit);

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

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

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

ES6为整数支持 二进制数字字面值,因此如果二进制字符串是不可变的,就像问题中的示例代码那样,人们可以直接键入它,就像它的前缀 0b0B那样:

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

另一个仅用于功能性 JS 实践的实现可以是

var bin2int = s => Array.prototype.reduce.call(s, (p,c) => p*2 + +c)
console.log(bin2int("101010"));
其中 +cString类型的 c强制转换为 Number类型的值以进行适当的加法。

我收集了所有其他人提出的建议,并创建了下面的函数,它有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>Examples: <br />
<em>110, 2, 10</em> => <em>6</em>; (110)<sub>2</sub> = 6<br />


<em>2d, 16, 10</em> => <em>45</em>; (2d)<sub>16</sub> = 45<br />
<em>45, 10, 16</em> => <em>2d</em>; 45 = (2d)<sub>16</sub><br />
<em>101101, 2, 16</em> => <em>2d</em>; (101101)<sub>2</sub> = (2d)<sub>16</sub>
</p>

供参考: 如果你想传递 2d作为一个十六进制数字,你需要发送它作为一个字符串,所以它是这样的: changeBase('2d', 16, 10)

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);
}

稍微修改了传统的二进制转换算法,使用了更多 ES6语法和自动特性:

  1. 将二进制序列字符串转换为 Array (假设它不是 传递为数组)

  2. 反向序列强制0索引从最右边的二进制文件开始 以二进制形式计算的数字为右-左

  3. Array 函数遍历 Array,执行 (2 ^ index)每个二进制数字[只有当二进制数字 = = 1](0位 总是产生0)

注: 二进制转换公式:

{其中 d = 二进制数字,i = 数组索引,n = 数组长度 -1(从右开始)}

N
∑(d * 2 ^ i)
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}).`);
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

@ Baptx@ Jon@ ikhvjs的注释为基础,下面的代码应该能够处理真正大的二进制字符串:

// ES10+
function bin2dec(binStr) {
const lastIndex = binStr.length - 1;


return Array.from(binStr).reduceRight((total, currValue, index) => (
(currValue === '1') ? total + (BigInt(2) ** BigInt(lastIndex - index)) : total
), BigInt(0));
}

或者,同样使用 for循环:

// ES10+
function bin2dec(binStr) {
const lastIndex = binStr.length - 1;
let total = BigInt(0);


for (let i = 0; i < binStr.length; i++) {
if (binStr[lastIndex - i] === '1') {
total += (BigInt(2) ** BigInt(i));
}
}


return total;
}

例如:

console.log(bin2dec('101')); // 5n


console.log(bin2dec('110101')); // 53n


console.log(bin2dec('11111111111111111111111111111111111111111111111111111')); // 9007199254740991n


console.log(bin2dec('101110110001101000111100001110001000101000101011001100000011101')); // 6741077324010461213n

为那些希望学习更多知识的人写了一个 博客文章