How to convert text to binary code in JavaScript?

后端 未结 13 1842
囚心锁ツ
囚心锁ツ 2020-11-28 05:00

Text to Binary Code

I want JavaScript to translate text in a textarea into binary code.

For example, if a user types in "TEST

13条回答
  •  不知归路
    2020-11-28 05:20

    1. traverse the string
    2. convert every character to their char code
    3. convert the char code to binary
    4. push it into an array and add the left 0s
    5. return a string separated by space

    Code:

    function textToBin(text) {
      var length = text.length,
          output = [];
      for (var i = 0;i < length; i++) {
        var bin = text[i].charCodeAt().toString(2);
        output.push(Array(8-bin.length+1).join("0") + bin);
      } 
      return output.join(" ");
    }
    textToBin("!a") => "00100001 01100001"
    

    Another way

    function textToBin(text) {
      return (
        Array
          .from(text)
          .reduce((acc, char) => acc.concat(char.charCodeAt().toString(2)), [])
          .map(bin => '0'.repeat(8 - bin.length) + bin )
          .join(' ')
      );
    }
    

提交回复
热议问题