How to convert text to binary code in JavaScript?

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

提交回复
热议问题