バイナリ文字列を数字に変換したい例
var binary = "1101000" // code for 104
var digit = binary.toString(10); // Convert String or Digit (But it does not work !)
console.log(digit);
それはどのように可能ですか?ありがとう
バイナリ文字列を数字に変換したい例
var binary = "1101000" // code for 104
var digit = binary.toString(10); // Convert String or Digit (But it does not work !)
console.log(digit);
それはどのように可能ですか?ありがとう
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);
ES6 は整数のバイナリ数値リテラル0b
をサポートしているため、問題のコード例のようにバイナリ文字列が不変の場合は、接頭辞またはを付けてそのまま入力でき0B
ます。
var binary = 0b1101000; // code for 104
console.log(binary); // prints 104
parseInt()
with radix が最良の解決策です(多くの人が言ったように):
しかし、parseInt なしで実装したい場合は、次の実装があります。
function bin2dec(num){
return num.split('').reverse().reduce(function(x, y, i){
return (y === '1') ? x + Math.pow(2, i) : x;
}, 0);
}