[Date Prev][Date Next] [Chronological] [Thread] [Top]

Re: iso8859 -> utf8 -> base64 code?



On Wed, 3 Sep 2003, Christian Nygaard wrote:

> Hi can somebody please post working iso8859 -> utf8 -> base64
> Perl/Python conversion code?

You can use MIME::Base64 in Perl, or if you don't want to use
a non-core module, use this:

#
# Given a string, return a de-mimed version.
# Can't use MIME::Base64 because it's not a core module.
#
# NB: I don't bother with line wraps, incorrect size, etc.
#
sub demime
{
    my $line = shift;
    $line =~ tr:A-Za-z0-9+/::cd;	# Ignore none-MIME
    $line =~ tr:A-Za-z0-9+/: -_:;	# Translate to uuencode
    $line =~ s/ /`/g;			# Spaces are obsolete?

    my $size = length($line);		# Work out size byte
    $size *= 3; $size /= 4;
    $line = chr(ord(' ') + $size) . $line;

    return join("", unpack("u", $line));
}

#
# En-mime same.
#
# Again, I don't restrict line length, so watch it!
#
sub enmime
{
    my $line = shift;
    my $result;

    $result = pack("u", $line);		# Convert to UU
    $result =~ s/^.//;			# Strip length byte
    $result =~ s/\n$//;
    $result =~ tr:` -_:AA-Za-z0-9+/:;	# Allow space->A

    my $size = length($line) % 3;	# Work out padding
    if ($size)
    {
	$size = 3 - $size;		# 1,2 -> 2,1
	my $pad = '=' x $size;
	$result =~ s/.{$size}$/$pad/;	# Padding replaces last $size bytes
    }

    return $result;
}

-- 
Dave Horsfall  DTM  VK2KFU  daveh@ci.com.au  Ph: +61 2 9906-7866  Fx: 9906-1556
Corinthian Engineering, Level 1, 401 Pacific Hwy, Artarmon, NSW 2064, Australia