How to convert binary representation of number from string to integer number in 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中将数字的二进制表示从字符串转换为整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在JavaScript中将数字的二进制表示从字符串转换为整数?
基础教程推荐
- 为什么我在 Vue.js 中得到 ERR_CONNECTION_TIMED_OUT? 2022-01-01
- 如何使用sencha Touch2在单页中显示列表和其他标签 2022-01-01
- Javascript 在多个元素上单击事件侦听器并获取目标 2022-01-01
- jQuery File Upload - 如何识别所有文件何时上传 2022-01-01
- 如何在特定日期之前获取消息? 2022-01-01
- 什么是不使用 jQuery 的经验技术原因? 2022-01-01
- Node.js 有没有好的索引/搜索引擎? 2022-01-01
- 每次设置弹出窗口的焦点 2022-01-01
- 如何使用 CSS 显示和隐藏 div? 2022-01-01
- WatchKit 支持 html 吗?有没有像 UIWebview 这样的控制器? 2022-01-01
