3

I got an assignment to convert a given string into binary and back to a string again.

The first part was easy

function stringToBinary(input) {
  var characters = input.split('');

  return characters.map(function(char) {
    return char.charCodeAt(0).toString(2)
  }).join('');
}

alert(stringToBinary('test'))

However I cannot get my head around how to break the resulting string into their bytes. I tried this so far:

function binaryToString(input) {
  var bits = input.split('');
  
  var byte = '';
  return bits.map(function(bit) {
    byte = byte + bit;
    
    if (byte.length == 8) {
      var char = byte; // how can I convert this to a character again?
      byte = '';
      return char;
    }
    
    return '';
  }).join('');
}

alert(binaryToString('1110100110010111100111110100'));

How can I convert a byte into a character again? And it also feels a bit odd. Is there a better, faster way to collect those bytes

1

3 Answers 3

5

There is a problem with your stringToBinary function. Converting a character to binary only leaves you with the least amount of bits. So you still need to convert it to an 8-bit string.

The other thing is, that you can just get the first 8 digits from your binary and trim your input as you go, like in the following example.

function stringToBinary(input) {
  var characters = input.split('');

  return characters.map(function(char) {
    const binary = char.charCodeAt(0).toString(2)
    const pad = Math.max(8 - binary.length, 0);
    // Just to make sure it is 8 bits long.
    return '0'.repeat(pad) + binary;
  }).join('');
}

function binaryToString(input) {
  let bytesLeft = input;
  let result = '';

  // Check if we have some bytes left
  while (bytesLeft.length) {
    // Get the first digits
    const byte = bytesLeft.substr(0, 8);
    bytesLeft = bytesLeft.substr(8);

    result += String.fromCharCode(parseInt(byte, 2));
  }

  return result;
}

const binary = stringToBinary('test');
console.log({
  binary,
  text: binaryToString(binary),
});

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, that really helped! I didn't know that I need leading zeros here.
When you use a transpiler (like babel) or you don't care about IE11 you can also use padStart like in Nina Scholz' answer.
0

First of all, you need to take the same length of the converted string as input for the conversion back to a string, by taking String#padStart with a length of 8 and a filling character of zero.

function stringToBinary(input) {
    var characters = input.split('');

    return characters
        .map(function(char) {
            return char.charCodeAt(0).toString(2).padStart(8, 0)
        })
        .join(' '); // show with space for each byte
                    // watch leading zero, which is missed in the former code
}

console.log(stringToBinary('test'))

The you need to take this string and split it into a length of eight characters and convert it back.

function binaryToString(input) {
    return input
        .match(/.{8}/g)                                    // take 8 characters
        .map(function(byte) {
            return String.fromCharCode(parseInt(byte, 2));
        })
        .join('');
}

console.log(binaryToString('01110100011001010111001101110100'));

While you are asking for a faster way, you could spread the splitted converted bytes to the fromCharCode function.

function binaryToString(input) {
    return String
        .fromCharCode(...input
            .match(/.{8}/g)
            .map(byte => parseInt(byte, 2))
        );
}

console.log(binaryToString('01110100011001010111001101110100'));

2 Comments

Thank you! That really helps. I didn't know that I need leading zeros. So is your solution expecting me to create the binary string with spaces?
no, it is just to show the leading zero and the length of eight characters.
0

I just worked on exact project right now, here are the functions to convert from text to binary and from binary to text:

function binaryToTexttConverter(str) {
  let wordArray = [];
  let message = str.split(" ").map((stack) => {
    let numberArray = parseInt(stack, 2);
    let letters = String.fromCharCode(numberArray);
    wordArray.push(letters);
  });
  let output = wordArray.join("");
  console.log(output);
  return output;
}

// binaryToTexttConverter("test binary"); 

*****************************************************************

function textToBinaryConverter(str) {
  let xterCodesArray = [];
  let splitted = str.split("");
  for (i = 0; i < splitted.length; i++) {
    let xterCodes = splitted[i].charCodeAt(splitted[i]);
    xterCodesArray.push(xterCodes.toString(2));
  }
  console.log(xterCodesArray.join(" "));
  return xterCodesArray.join(" ");
}

// textToBinaryConverter("test string");

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.