How to convert text to binary code in JavaScript?

后端 未结 13 1833
囚心锁ツ
囚心锁ツ 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:38

    What you should do is convert every char using charCodeAt function to get the Ascii Code in decimal. Then you can convert it to Binary value using toString(2):

    HTML:

    
    
    
    

    JS:

    function convert() {
      var output = document.getElementById("ti2");
      var input = document.getElementById("ti1").value;
      output.value = "";
      for (var i = 0; i < input.length; i++) {
          output.value += input[i].charCodeAt(0).toString(2) + " ";
      }
    }
    

    And here's a fiddle: http://jsfiddle.net/fA24Y/1/

提交回复
热议问题