Convert binary string to string in javascript

I have a Binary string and I want to convert it into a string format. here is the function,

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

stringConversion(00000000000000000000000000001011);

The output I want is “00000000000000000000000000001011” but it is giving me “521”

Answer

In JS a number token that starts with a 0 and does not contain a 9 is read in octal base. So the interpreter convert your number into a decal base, and you obtain a different number: 01011 => (1011)8 = (521)10.

If the token stats with 0b it is read as binary string also, so you could just append it to your number: 0b1011 => (1011)2 = (11)10.

Now if you want to convert a bit string, well, actually it should be literally a string. You should do something like stringConversion('00000000000000000000000000001011');

I wrote some code that helps you to find the right way to encode/decode a binary string into a UNSIGNED (theoretically) infinite number. If you want to keep sign, you should provide some more informations to the binary string, like for example a fixed length or pretend that the first bit is the sign.

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

Now, this is the conventional way to represent a binary integer, but if your bit string should represent something different, a float for example, the code would drastically change. You could also define your own way to parse that string. There are also many underlying assumptions, which I will not dig into (like endian, and other finite memory representation stuffs).

Leave a Reply

Your email address will not be published. Required fields are marked *