如何在JavaScript中将数字的二进制表示从字符串转换为整数?
有人可以给我一点建议吗?
Can anybody give me a little advice please?
我有一个字符串,例如01001011",我需要做的是反转它,所以我使用 .split('')
而不是 .reverse()
现在我需要将数组作为字符串读取并将其转换为整数.有可能吗?
I have a string, for example "01001011" and what I need to do is to reverse it, so I used .split('')
than .reverse()
and now I need to read the array as a string and convert it to integer. Is it possible?
谢谢
推荐答案
如果要将数组转换回字符串,请使用 join()
(MDN) 并将字符串转换为整数使用 parseInt()
(MDN).后者的第二个参数是可选的基数.
If you want to convert the array back to a string use join()
(MDN) and for converting a string to an integer use parseInt()
(MDN). The second argument of the later is an optional radix.
JavaScript 会尝试确定要使用的基数,但要确保始终手动添加基数.引用自 MDN:
JavaScript will try to determine, what radix to use, but to be sure you should always add your radix manually. Citing from MDN:
如果 radix 未定义或为 0,JavaScript 假定如下:
If radix is undefined or 0, JavaScript assumes the following:
如果输入字符串以0x"或0X"开头,则基数为16(十六进制).
If the input string begins with "0x" or "0X", radix is 16 (hexadecimal).
如果输入字符串以0"开头,则基数为八(八进制).这个特性是非标准的,一些实现故意不支持它(而是使用基数 10).因此,在使用 parseInt 时始终指定一个基数.
If the input string begins with "0", radix is eight (octal). This feature is non-standard, and some implementations deliberately do not support it (instead using the radix 10). For this reason always specify a radix when using parseInt.
如果输入字符串以任何其他值开头,则基数为 10(十进制).
If the input string begins with any other value, the radix is 10 (decimal).
所以在你的情况下,下面的代码应该可以工作:
So in your case the following code should work:
var a = '01001011';
var b = parseInt( a.split('').reverse().join(''), 2 );
或者只是(如果你想转换起始字符串,不反转):
or just (if you would want to convert the starting string, without the reversal):
var b = parseInt( a, 2 );
相关文章