How to convert text to binary code in JavaScript?

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

    Thank you Majid Laissi for your answer

    I made 2 functions out from your code:

    the goal was to implement convertation of string to VARBINARY, BINARY and back

    const stringToBinary = function(string, maxBytes) {
      //for BINARY maxBytes = 255
      //for VARBINARY maxBytes = 65535
      let binaryOutput = '';
      if (string.length > maxBytes) {
        string = string.substring(0, maxBytes);
      }
    
      for (var i = 0; i < string.length; i++) {
        binaryOutput += string[i].charCodeAt(0).toString(2) + ' ';
      }
    
      return binaryOutput;
    };
    

    and backward convertation:

    const binaryToString = function(binary) {
      const arrayOfBytes = binary.split(' ');
    
      let stringOutput = '';
    
      for (let i = 0; i < arrayOfBytes.length; i++) {
        stringOutput += String.fromCharCode(parseInt(arrayOfBytes[i], 2));
      }
    
      return stringOutput;
    };
    

    and here is a working example: https://jsbin.com/futalidenu/edit?js,console

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

    Try this:

    String.prototype.toBinaryString = function(spaces = 0) {
        return this.split("").map(function(character) {
            return character.charCodeAt(0).toString(2);
        }).join(" ".repeat(spaces));
    }
    

    And use it like this:

    "test string".toBinaryString(1); // with spaces
    "test string".toBinaryString(); // without spaces
    "test string".toBinaryString(2); // with 2 spaces
    
    0 讨论(0)
  • 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(' ')
      );
    }
    
    0 讨论(0)
  • 2020-11-28 05:21

    The other answers will work for most cases. But it's worth noting that charCodeAt() and related don't work with UTF-8 strings (that is, they throw errors if there are any characters outside the standard ASCII range). Here's a workaround.

    // UTF-8 to binary
    var utf8ToBin = function( s ){
        s = unescape( encodeURIComponent( s ) );
        var chr, i = 0, l = s.length, out = '';
        for( ; i < l; i ++ ){
            chr = s.charCodeAt( i ).toString( 2 );
            while( chr.length % 8 != 0 ){ chr = '0' + chr; }
            out += chr;
        }
        return out;
    };
    
    // Binary to UTF-8
    var binToUtf8 = function( s ){
        var i = 0, l = s.length, chr, out = '';
        for( ; i < l; i += 8 ){
            chr = parseInt( s.substr( i, 8 ), 2 ).toString( 16 );
            out += '%' + ( ( chr.length % 2 == 0 ) ? chr : '0' + chr );
        }
        return decodeURIComponent( out );
    };
    

    The escape/unescape() functions are deprecated. If you need polyfills for them, you can check out the more comprehensive UTF-8 encoding example found here: http://jsfiddle.net/47zwb41o

    0 讨论(0)
  • 2020-11-28 05:22
    var UTF8ToBin=function(f){for(var a,c=0,d=(f=unescape(encodeURIComponent(f))).length,b="";c<d;c++){for(a=f.charCodeAt(c).toString(2);a.length%8!=0;){a="0"+a}b+=a}return b},binToUTF8=function(f){for(var a,c=0,d=f.length,b="";c<d;c+=8){b+="%"+((a=parseInt(f.substr(c,8),2).toString(16)).length%2==0?a:"0"+a)}return decodeURIComponent(b)};
    

    This is a small minified JavaScript Code to convert UTF8 to Binary and Vice versa.

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

    8-bit characters with leading 0

    'sometext'
            .split('')
            .map((char) => '00'.concat(char.charCodeAt(0).toString(2)).slice(-8))
            .join(' ');
    

    If you need 6 or 7 bit, just change .slice(-8)

    0 讨论(0)
提交回复
热议问题