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 does not work !)
console.log(digit);
How is it possible? Thanks
怎么可能?谢谢
5 个解决方案
#1
96
The parseInt
function converts strings to numbers, and it takes a second argument specifying the base in which the string representation is:
parseInt函数将字符串转换为数字,它接受第二个参数,指定字符串表示的基数:
var digit = parseInt(binary, 2);
看它的实际应用。
#2
#3
8
parseInt()
with radix is a best solution (as was told by many):
parseInt() with radix是最好的解决方案(正如许多人所说):
But if you want to implement it without parseInt, here is an implementation:
但是,如果您想在不使用parseInt的情况下实现它,这里有一个实现:
function bin2dec(num){
return num.split('').reverse().reduce(function(x, y, i){
return (y === '1') ? x + Math.pow(2, i) : x;
}, 0);
}
#4
7
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
:
ES6支持整数的二进制数字文本,因此,如果二进制字符串是不可变的,就像问题中的示例代码一样,您可以将其输入为前缀0b或0b:
var binary = 0b1101000; // code for 104
console.log(binary); // prints 104
#5
0
Another implementation just for functional JS practicing could be
另一个仅用于函数JS实践的实现可能是
var bin2int = s => Array.prototype.reduce.call(s, (p,c) => p*2 + +c)
console.log(bin2int("101010"));
+c
coerces
String
type
c
to a
Number
type value for proper addition.
#1
96
The parseInt
function converts strings to numbers, and it takes a second argument specifying the base in which the string representation is:
parseInt函数将字符串转换为数字,它接受第二个参数,指定字符串表示的基数:
var digit = parseInt(binary, 2);
看它的实际应用。
#2
9
Use the radix parameter of parseInt
:
使用parseInt的基数参数:
var binary = "1101000";
var digit = parseInt(binary, 2);
console.log(digit);
#3
8
parseInt()
with radix is a best solution (as was told by many):
parseInt() with radix是最好的解决方案(正如许多人所说):
But if you want to implement it without parseInt, here is an implementation:
但是,如果您想在不使用parseInt的情况下实现它,这里有一个实现:
function bin2dec(num){
return num.split('').reverse().reduce(function(x, y, i){
return (y === '1') ? x + Math.pow(2, i) : x;
}, 0);
}
#4
7
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
:
ES6支持整数的二进制数字文本,因此,如果二进制字符串是不可变的,就像问题中的示例代码一样,您可以将其输入为前缀0b或0b:
var binary = 0b1101000; // code for 104
console.log(binary); // prints 104
#5
0
Another implementation just for functional JS practicing could be
另一个仅用于函数JS实践的实现可能是
var bin2int = s => Array.prototype.reduce.call(s, (p,c) => p*2 + +c)
console.log(bin2int("101010"));
+c
coerces
String
type
c
to a
Number
type value for proper addition.