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

Re: iso8859 -> utf8 -> base64 code?



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

print attr($attr_type, $value);

# Print attribute and value in LDIF format
sub attr {
    my($name, $val) = @_;

    $val = iso2utf($val);
    if ($val =~ /^[ \t]|[ \t]$/ || $val =~ /[\0\r\n\f\177\200-\377]/) {
	return ($name, ":: ", base64($val), "\n");
    } else {
	return ($name, ": ", $val, "\n");
    }
}

# Convert iso8859-1 to UTF-8
sub iso2utf {
    my($str) = @_;
    $str =~ s/([\200-\377])/
	      pack('CC', 0xC0 + (ord($1) >> 6), (ord($1) & 0xBF))/gex;
    $str;
}

# Base64-encode value
sub base64 {
    my $res = pack('u', @_);
    $res =~ s/.(.*)\n/$1/g;
    $res =~ tr%\` -_%AA-Za-z0-9+/%;
    my $padding = (3 - length($_[0]) % 3) % 3;
    $res =~ s/.{$padding}$/'=' x $padding/e if $padding;
    $res;
}

-- 
Hallvard