如何在JavaScript中将数字的二进制表示从字符串转换为整数?

How to convert binary representation of number from string to integer number in JavaScript?(如何在JavaScript中将数字的二进制表示从字符串转换为整数?)
本文介绍了如何在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 );

这篇关于如何在JavaScript中将数字的二进制表示从字符串转换为整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

在开发JS过程中,会经常遇到两个小数相运算的情况,但是运算结果却与预期不同,调试一下发现计算结果竟然有那么长一串尾巴。如下图所示: 产生原因: JavaScript对小数运算会先转成二进制,运算完毕再转回十进制,过程中会有丢失,不过不是所有的小数间运算会
问题描述: 在javascript中引用js代码,然后导致反斜杠丢失,发现字符串中的所有\信息丢失。比如在js中引用input type=text onkeyup=value=value.replace(/[^\d]/g,) ,结果导致正则表达式中的\丢失。 问题原因: 该字符串含有\,javascript对字符串进行了转
Rails/Javascript: How to inject rails variables into (very) simple javascript(Rails/Javascript:如何将 rails 变量注入(非常)简单的 javascript)
CoffeeScript always returns in anonymous function(CoffeeScript 总是以匿名函数返回)
Ordinals in words javascript(javascript中的序数)
getFullYear returns year before on first day of year(getFullYear 在一年的第一天返回前一年)