Monday, May 31, 2010

ascii85 encoder in perl

I got bored, here's an ascii85 encoder in perl (Adobe's take on it, anyway). check out wikipedia for more info.


use strict;

local $/;
my @foo;
print "<~";
@foo = unpack("C*", <>);
while (scalar(@foo) > 0) {
my (@a, @buf, $x, $i);
@a = splice(@foo, 0, 4);

$x =
(defined($a[0]) ? ($a[0] << 24) : 0) | (defined($a[1]) ? ($a[1] << 16) : 0) |
(defined($a[2]) ? ($a[2] << 8) : 0) | (defined($a[3]) ? ($a[3] << 0) : 0);
if (@a == 4 && $x == 0) { print "z"; next; }
for $i (1 .. 5) {
$buf[ 5 - $i ] = chr(($x % 85) + 33);
$x /= 85;
}
print @buf[ 0 .. scalar(@a) ];
}
print "~>\n";

No comments: