How can I convert a string to numeric values (should be reversible) using JavaScript?

前端 未结 2 676
不知归路
不知归路 2021-01-15 12:36

How can I convert a JavaScript string into a unique numeric value such that you can convert the numeric value back to the string? The length of the numeric value doesn\'t ma

相关标签:
2条回答
  • 2021-01-15 13:18

    Strings are actually stored as numbers. We can get the ascii code for each letter in the string and concat them into one big number forcing each number to be three digits so we can easily reverse the process.

    function convertToNumber(str){
      var number = "";
      for (var i=0; i<str.length; i++){
        charCode = ('000' + str[i].charCodeAt(0)).substr(-3);
        number += charCode;
      }
      return number;
    }
    alert(convertToNumber("SO does my homework")); //console.log is better
    

    Now we can take this long number and turn it back into a string by pulling the numbers off three at a time and using the opposite of char.charCodeAt(0) which is String.fromCharCode(num):

    function convertToString(numbers){
      origString = "";
      numbers = numbers.match(/.{3}/g);
      for(var i=0; i < numbers.length; i++){
        origString += String.fromCharCode(numbers[i]);
      }
      return origString;
    }
    alert(convertToString("083079032100111101115032109121032104111109101119111114107"));  //console.log is better
    
    0 讨论(0)
  • 2021-01-15 13:28

    Strings and Numbers:

    A string can be described as a series of bytes with encoding. That results in characters being shown instead of the byte values.

    to get the character code for a certain character you would call the charCodeAt method on a string.

    "a".charCodeAt(0); // => 97
    "A".charCodeAt(0); // => 65
    

    so as you can see there is a numeric value for each letter and it's variants. Now the next problem is how to store these numbers. For example you cannot just add them together because:

    97 + 65 = 162;
    String.fromCharCode(162); // => ¢
    

    The best solution is probably to store them in an array so they can be easy reassembled later.

    var StringTools = {
      stringToNumbersArray: function(data){
        return data.split('').map(function(c){return c.charCodeAt(0);});
      },
      numbersArrayToString: function(arr){
        return arr.map(function(n){return String.fromCharCode(n)}).join('');
      }
    }
    
    StringTools.stringToNumbersArray("Hello");
    // => [72, 101, 108, 108, 111]
    StringTools.numbersArrayToString([72, 101, 108, 108, 111])
    // => "Hello"
    

    Encoding String Values:

    Now it's entirely likely that you are wanting to support something that is not an array (a single string of numbers that reflects the entire word). To do this you need as many digits as would be required to store the largest value in the set, which is 3. So we can push these numbers together into a single number as long as we know this length and we can pull them apart later.

    [72, 101, 108, 108, 111].reduce(function(memo, n){
      return memo + ("000" + n).slice(-3);
    }, "");
    // => "072101108108111"
    

    but as you can see this isn't a real number since the 0 at the beginning is a significant digit. More commonly hexadecimal is used to store these types of values. Consider that each number can be converted to hexadecimal using the toString method where the argument is the radix (base of numbers, 16 for hex).

    [72, 101, 108, 108, 111].reduce(function(memo, n){
      return memo + ("00" + n.toString(16)).slice(-2);
    }, "");
    // => "48656c6c6f"
    

    as you can see this saved us a few characters because we know that 4 bits can be stored in a single base 16 number (1111 === 15) and so you can get full byte of storage using just 2 base 16 numbers (16 * 16 = 256).

    To reverse the hexadecimal code out to the original string you only need to split the string into pairs of 2 and convert them back to base 10, then use String.fromCharCode() on the result to get each character.

    "48656c6c6f".split("").reduce(function(result, c, idx, list){
      if (idx % 2 != 0) {
        result += String.fromCharCode(parseInt(list[idx-1] + c, 16));
      }
      return result;
    }, "");
    
    0 讨论(0)
提交回复
热议问题