how to convert binary string to decimal?

后端 未结 9 2186
佛祖请我去吃肉
佛祖请我去吃肉 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 05:06

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

    var digit = parseInt(binary, 2);
    

    See it in action.

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

    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:

    changeBase(1101000, 2, 10) => 104
    

    Run Code Snippet to try it yourself:

    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)

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

    ES6 supports binary numeric literals for 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 0b or 0B:

    var binary = 0b1101000; // code for 104
    console.log(binary); // prints 104
    
    0 讨论(0)
提交回复
热议问题