how to convert binary string to decimal?

后端 未结 9 2185
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-28 04:41

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          


        
相关标签:
9条回答
  • 2020-11-28 04:47

    Use the radix parameter of parseInt:

    var binary = "1101000";
    var digit = parseInt(binary, 2);
    console.log(digit);
    
    0 讨论(0)
  • 2020-11-28 04:49
    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);
    }
    
    0 讨论(0)
  • 2020-11-28 04:53

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

    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)

    NOTE: Binary conversion formula:

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

    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}).`);
    
    0 讨论(0)
  • 2020-11-28 04:56
            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
    
    0 讨论(0)
  • 2020-11-28 04:56

    Another implementation just for functional JS practicing could be

    var bin2int = s => Array.prototype.reduce.call(s, (p,c) => p*2 + +c)
    console.log(bin2int("101010"));
    where +c coerces String type c to a Number type value for proper addition.

    0 讨论(0)
  • 2020-11-28 05:01

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

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

      function bin2dec(num){
        return num.split('').reverse().reduce(function(x, y, i){
          return (y === '1') ? x + Math.pow(2, i) : x;
        }, 0);
      }
    
    0 讨论(0)
提交回复
热议问题