首页 > 解决方案 > 在javascript中将二进制字符串转换为字符串

问题描述

我有一个二进制字符串,我想将其转换为字符串格式。这是功能,

let stringConversion = (n) => {
  let convertToString = n.toString();
  console.log(convertToString);
};

stringConversion(00000000000000000000000000001011);

我想要的输出是“00000000000000000000000000001011”,但它给了我“521”

标签: javascripttostring

解决方案


在 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)');

现在,这是表示二进制整数的传统方式,但如果您的位字符串应该表示不同的东西,例如浮点数,代码将发生巨大变化。您还可以定义自己的方式来解析该字符串。还有许多潜在的假设,我不会深入研究(如字节序和其他有限内存表示的东西)。


推荐阅读