How to convert text to binary code in JavaScript?

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

    Just a hint into the right direction

    var foo = "TEST",
        res = [ ];
    
    foo.split('').forEach(function( letter ) {
        var bin     = letter.charCodeAt( 0 ).toString( 2 ),
            padding = 8 - bin.length;
    
        res.push( new Array( padding+1 ).join( '0' ) + bin );
    });
    
    console.log( res );
    
    0 讨论(0)
  • 2020-11-28 05:37
    var PADDING = "00000000"
    
    var string = "TEST"
    var resultArray = []
    
    for (var i = 0; i < string.length; i++) {
      var compact = string.charCodeAt(i).toString(2)
      var padded  = compact.substring(0, PADDING.length - compact.length) + compact
    
      resultArray.push(padded)
    }
    
    console.log(resultArray.join(" "))
    
    0 讨论(0)
  • 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:

    <input id="ti1" value ="TEST"/>
    <input id="ti2"/>
    <button onClick="convert();">Convert!</button>
    

    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/

    0 讨论(0)
  • 2020-11-28 05:40

    Here's a pretty generic, native implementation, that I wrote some time ago,

    // ABC - a generic, native JS (A)scii(B)inary(C)onverter.
    // (c) 2013 Stephan Schmitz <eyecatchup@gmail.com>
    // License: MIT, http://eyecatchup.mit-license.org
    // URL: https://gist.github.com/eyecatchup/6742657
    var ABC = {
      toAscii: function(bin) {
        return bin.replace(/\s*[01]{8}\s*/g, function(bin) {
          return String.fromCharCode(parseInt(bin, 2))
        })
      },
      toBinary: function(str, spaceSeparatedOctets) {
        return str.replace(/[\s\S]/g, function(str) {
          str = ABC.zeroPad(str.charCodeAt().toString(2));
          return !1 == spaceSeparatedOctets ? str : str + " "
        })
      },
      zeroPad: function(num) {
        return "00000000".slice(String(num).length) + num
      }
    };
    

    and to be used as follows:

    var binary1      = "01100110011001010110010101101100011010010110111001100111001000000110110001110101011000110110101101111001",
        binary2      = "01100110 01100101 01100101 01101100 01101001 01101110 01100111 00100000 01101100 01110101 01100011 01101011 01111001",
        binary1Ascii = ABC.toAscii(binary1),
        binary2Ascii = ABC.toAscii(binary2);
    
    console.log("Binary 1:                   " + binary1);
    console.log("Binary 1 to ASCII:          " + binary1Ascii);
    console.log("Binary 2:                   " + binary2);
    console.log("Binary 2 to ASCII:          " + binary2Ascii);
    console.log("Ascii to Binary:            " + ABC.toBinary(binary1Ascii));     // default: space-separated octets
    console.log("Ascii to Binary /wo spaces: " + ABC.toBinary(binary1Ascii, 0));  // 2nd parameter false to not space-separate octets
    

    Source is on Github (gist): https://gist.github.com/eyecatchup/6742657

    Hope it helps. Feel free to use for whatever you want (well, at least for whatever MIT permits).

    0 讨论(0)
  • 2020-11-28 05:41

    This might be the simplest you can get:

    function text2Binary(string) {
        return string.split('').map(function (char) {
            return char.charCodeAt(0).toString(2);
        }).join(' ');
    }
    
    0 讨论(0)
  • 2020-11-28 05:42

    this seems to be the simplified version

    Array.from('abc').map((each)=>each.charCodeAt(0).toString(2)).join(" ")
    
    0 讨论(0)
提交回复
热议问题