how to convert binary string to decimal?

后端 未结 9 2220
佛祖请我去吃肉
佛祖请我去吃肉 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: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;
    }
    
    
    
    
    
    
    
    

    Hint:
    Try 110, 2, 10 and it will return 6; (110)2 = 6
    or 2d, 16, 10 => 45 meaning: (2d)16 = 45
    or 45, 10, 16 => 2d meaning: 45 = (2d)16
    or 2d, 2, 16 => 2d meaning: (101101)2 = (2d)16

    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)

提交回复
热议问题