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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10258828/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 00:31:49  来源:igfitidea点击:

how to convert binary string to decimal?

javascriptnode.js

提问by Jon

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

这怎么可能?谢谢

回答by Jon

The parseIntfunction converts strings to numbers, and it takes a second argument specifying the base in which the string representation is:

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

var digit = parseInt(binary, 2);

See it in action.

看到它在行动

回答by GOTO 0

ES6 supports binary numeric literalsfor integers, so if the binary string is immutable, as in the example code in the question, one could just type it in as it is with the prefix 0bor 0B:

ES6 支持整数的二进制数字字面量,因此如果二进制字符串是不可变的,如问题中的示例代码所示,您可以按原样输入它,并使用前缀0b0B

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

回答by Salvador Dali

parseInt()with radix is a best solution (as was told by many):

parseInt()with radix 是最好的解决方案(正如许多人所说):

But if you want to implement it without parseInt, here is an implementation:

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

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

回答by phihag

Use the radixparameter of parseInt:

使用radix参数parseInt

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

回答by Iliyan Shalvarkov

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

回答by Md Shahriar

        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

回答by Redu

Another implementation just for functional JS practicing could be

另一个仅用于功能性 JS 练习的实现可能是

var bin2int = s => Array.prototype.reduce.call(s, (p,c) => p*2 + +c)
console.log(bin2int("101010"));
其中+c+c胁迫StringString键入ccNumberNumber适当加成类型值。

回答by Mohammad Musavi

I gathered all what others have suggested and created following function which has 3 arguments, the number and the base which that number has come from and the base which that number is going to be on:

我收集了所有其他人的建议并创建了以下函数,该函数具有 3 个参数,该数字来自的数字和基数以及该数字将要基于的基数:

changeBase(1101000, 2, 10) => 104

Run Code Snippet to try it yourself:

运行 Code Snippet 自己尝试一下:

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>

FYI: If you want to pass 2d as hex number, you need to send it as a string so it goes like this: changeBase('2d', 16, 10)

仅供参考:如果要将 2d 作为十六进制数传递,则需要将其作为字符串发送,如下所示: changeBase('2d', 16, 10)

回答by Isaac

Slightly modified conventional binary conversion algorithm utilizing some more ES6 syntax and auto-features:

使用更多 ES6 语法和自动功能对传统二进制转换算法稍作修改:

  1. Convert binary sequence string to Array (assuming it wasnt already passed as array)

  2. Reverse sequence to force 0 index to start at right-most binary digit as binary is calculated right-left

  3. 'reduce' Array function traverses array, performing summation of (2^index) per binary digit [only if binary digit === 1] (0 digit always yields 0)

  1. 将二进制序列字符串转换为数组(假设它尚未作为数组传递)

  2. 反向顺序强制 0 索引从最右边的二进制数字开始,因为二进制是从右向左计算的

  3. 'reduce' Array 函数遍历数组,对每个二进制数字执行 (2^index) 求和 [仅当二进制数字 === 1] (0 数字总是产生 0)

NOTE: Binary conversion formula:

注意:二进制转换公式:

{where d=binary digit, i=array index, n=array length-1 (starting from right)}

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

n
∑ (d * 2^i)
i=0

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