javascript - 在javascript中将二进制字符串转换为字符串
问题描述
我有一个二进制字符串,我想将其转换为字符串格式。这是功能,
let stringConversion = (n) => {
let convertToString = n.toString();
console.log(convertToString);
};
stringConversion(00000000000000000000000000001011);
我想要的输出是“00000000000000000000000000001011”,但它给了我“521”
解决方案
在 JS 中,以 a 开头0
且不包含 a的数字标记9
以八进制读取。因此,解释器将您的号码转换为贴花底座,您将获得不同的号码:01011 => (1011)8 = (521)10
.
如果带有它的令牌统计信息0b
也被读取为二进制字符串,那么您只需将其附加到您的号码:0b1011 => (1011)2 = (11)10
.
现在,如果你想转换一个位字符串,那么实际上它应该是一个字符串。你应该做类似的事情stringConversion('00000000000000000000000000001011');
我编写了一些代码来帮助您找到将二进制字符串编码/解码为UNSIGNED(理论上)无限数的正确方法。如果要保留符号,则应为二进制字符串提供更多信息,例如固定长度或假装第一位是符号。
function binary2number(bitStr) {
// initialize the result to 0
let result = 0;
for (let bit of bitStr) {
// shift the current result one bit to the left
result <<= 1;
// adding the current bit
result += !!parseInt(bit);
}
return result;
};
function number2binary(num, minBitLength=0) {
// converting the number to a string in base 2
let result = num.toString(2)
// concatenate the missing '0' up to minBitLength
while (result.length < minBitLength) {
result = '0' + result;
}
return result;
}
console.log('00000000000000000000000000001011 (in 8 base) is interpreted as' ,
00000000000000000000000000001011, '(in 10 base)');
console.log('00000000000000000000000000001011 =>',
binary2number('00000000000000000000000000001011'));
console.log('11 =>', number2binary(11, 32), '(32 bits = unsigned int commonly)');
console.log('11 =>', number2binary(11), '(for short)');
现在,这是表示二进制整数的传统方式,但如果您的位字符串应该表示不同的东西,例如浮点数,代码将发生巨大变化。您还可以定义自己的方式来解析该字符串。还有许多潜在的假设,我不会深入研究(如字节序和其他有限内存表示的东西)。
推荐阅读
- python - 在尝试安装 dm-sonnet 包时,我在 python-2.7 中面临“从 setuptools import find_namespace_packages”错误。任何可能的解决方案?
- maven - Git runner - 下载依赖项的问题
- apache-spark - 通过拆分对具有连接字符串的数据集以及火花中的列的单个字符串进行排序
- airflow - 启动 Airflow 网络服务器失败并出现 sqlalchemy.exc.NoInspectionAvailable:没有可用的检查系统
- ggplot2 - ggplot 具有共同密度的多个密度
- java - 如何使用 project-defaults yaml 配置消息传递 activemq - thorntail 或 swarm
- ajax - 通过ajax发送数据到本地ip地址(例如192.168.1.100)
- sql - '将参数值从 String 转换为 Int32 失败/-------
- angular - 中止管道执行
- apache-spark - 如何结束 Spark 提交和接受状态