如何在JavaScript中将数字的二进制表示形式从字符串转换为整数? [英] How to convert binary representation of number from string to integer number in 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 ).后者的第二个参数是一个可选的基数.
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:
如果未定义基数或为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 );
这篇关于如何在JavaScript中将数字的二进制表示形式从字符串转换为整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!