Base64 encoding vs Ascii85 encoding

前端 未结 3 961
说谎
说谎 2020-12-31 08:02

My project at work is using the Jackson JSON serializer to convert a bunch of Java objects into Strings in order to send them to REST services.

Some of these objects

3条回答
  •  半阙折子戏
    2020-12-31 08:48

    ASCII85 is a nice encoding to use to save that extra bit of space. But it outputs many characters that would need to be escaped if naively sent over HTTP. Base64 encoding has a variant that can be sent over HTTP without any escaping.

    Here's a javascript ASCII85 encoder in case anyone needs to try:

    // By Steve Hanov. Released to the public domain.
    function encodeAscii85(input) {
      var output = "<~";
      var chr1, chr2, chr3, chr4, chr, enc1, enc2, enc3, enc4, enc5;
      var i = 0;
    
      while (i < input.length) {
        // Access past the end of the string is intentional.
        chr1 = input.charCodeAt(i++);
        chr2 = input.charCodeAt(i++);
        chr3 = input.charCodeAt(i++);
        chr4 = input.charCodeAt(i++);
    
        chr = ((chr1 << 24) | (chr2 << 16) | (chr3 << 8) | chr4) >>> 0;
    
        enc1 = (chr / (85 * 85 * 85 * 85) | 0) % 85 + 33;
        enc2 = (chr / (85 * 85 * 85) | 0) % 85 + 33;
        enc3 = (chr / (85 * 85) | 0 ) % 85 + 33;
        enc4 = (chr / 85 | 0) % 85 + 33;
        enc5 = chr % 85 + 33;
    
        output += String.fromCharCode(enc1) +
          String.fromCharCode(enc2);
        if (!isNaN(chr2)) {
          output += String.fromCharCode(enc3);
          if (!isNaN(chr3)) {
            output += String.fromCharCode(enc4);
            if (!isNaN(chr4)) {
              output += String.fromCharCode(enc5);
            }
          }
        }
      }
    
      output += "~>";
    
      return output;
    }
    
    

提交回复
热议问题