The Challenge
Write a program that can take an input of a single-line string containing any ASCII printable characters, and output the same string encoded in Base85 (using a big-endian convention). You can assume that the input will always be ≤ 100 characters.
A Guide to Base85
Four octets are encoded into (usually) five Base85 characters.
Base85 characters range from
!
tou
(ASCII 33 - 117) andz
(ASCII 122).To encode, you continuously perform division by 85 on the four octets (a 32-bit number), and add 33 to the remainder (after each division) to get the ASCII character for the encoded value. For example, the first application of this process produces the rightmost character in the encoded block.
If a set of four octets contains only null bytes, they are encoded as a
z
instead of!!!!!
.If the last block is shorter than four octets, it's padded with null bytes. After encoding, the same number of characters that were added as padding, are removed from the end of the output.
The encoded value should be preceded by
<~
and followed by~>
.The encoded value should contain no whitespace (for this challenge).
Examples
In: easy
Out: <~ARTY*~>
In: test
Out: <~FCfN8~>
In: code golf
Out: <~@rGmh+D5V/Ac~>
In: Programming Puzzles
Out: <~:i^JeEa`g%Bl7Q+:j%)1Ch7Y~>
The following snippet will encode a given input to Base85.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><script>String.prototype.toAscii85=function(){if(""==this)return"<~~>";for(var r=[],t=0;t<this.length;t+=4){for(var i=(this.substr(t,4)+"\x00\x00\x00").substr(0,4),o=0,n=0;4>n;n++)o=256*o+i.charCodeAt(n);var s=[];for(n=0;5>n;n++){var e=o%85;o=(o-e)/85,s.unshift(String.fromCharCode(e+33))}r=r.concat(s)}var a=4-this.length%4;return 4!=a&&r.splice(-a,a),"<~"+r.join("").replace(/!!!!!/g,"z")+"~>"};</script><style>#in,#out{margin:20px;width:400px;resize:none}</style><input id="in" type="text" value="Base85"><button onclick="$('#out').text($('#in').val().toAscii85())">Submit</button><br><textarea id="out" rows=5 disabled></textarea>