将二进制字符串转换为 javascript 中的字符串

Convert binary string to string in javascript

我有一个二进制字符串,我想将它转换成字符串格式。 这是函数,

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

stringConversion(00000000000000000000000000001011);

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

在 JS 中,以 0 开头且不包含 9 的数字标记以八进制形式读取。因此解释器将您的数字转换为贴花基础,您将获得一个不同的数字:01011 => (1011)8 = (521)10.

如果带有 0b 的令牌统计信息也被读取为二进制字符串,因此您可以将其附加到您的号码:0b1011 => (1011)2 = (11)10.

现在如果你想转换一个位串,嗯,实际上它应该是字面上的字符串。你应该做类似 stringConversion('00000000000000000000000000001011');

的事情

我写了一些代码,可以帮助您找到将二进制字符串 encode/decode 转换为 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)');

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