how to convert binary string to decimal?
我想把二进制字符串转换成数字例如
1 2 3 | var binary ="1101000" // code for 104 var digit = binary.toString(10); // Convert String or Digit (But it does not work !) console.log(digit); |
怎么可能?谢谢
在
1 | var digit = parseInt(binary, 2); |
看到它在行动。 </P >
es6支二值文字的方法integers,所以如果二进制字符串是immutable为实例,在代码中的问题,一个可能是在AS型,它是与
1 2 | var binary = 0b1101000; // code for 104 console.log(binary); // prints 104 |
但如果你想执行它没有parseint,这里是一个实现: </P >
1 2 3 4 5 | function bin2dec(num){ return num.split('').reverse().reduce(function(x, y, i){ return (y === '1') ? x + Math.pow(2, i) : x; }, 0); } |
使用中的参数
1 2 3 | var binary ="1101000"; var digit = parseInt(binary, 2); console.log(digit); |
1 2 3 4 5 6 7 8 9 10 11 12 | 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); } |
另一个方法是执行功能与实践的可能 </P >
1 2 | var bin2int = s => Array.prototype.reduce.call(s, (p,c) => p*2 + +c) console.log(bin2int("101010")); |
在
我gathered全是什么人有suggested和创建下面的函数,这有3 arguments,号和号基地这是有来从和基地,这是要去数是: </P >
1 | changeBase(1101000, 2, 10) => 104 |
代码段的运行到它自己的努力: </P >
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | 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)); }); |
1 2 3 | #lblResult{ padding: 20px; } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"> <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> |
</P >
介绍:如果你想通的2D为十六进制数,你需要发送它作为一个字符串,它是这样的: