Math::Base36 - Encoding and decoding of base36 strings


Math-Base36 documentation Contained in the Math-Base36 distribution.

Index


Code Index:

NAME

Top

Math::Base36 - Encoding and decoding of base36 strings

SYNOPSIS

Top

  use Math::Base36 ':all';

  $b36 = encode_base36( $number );
  $number = decode_base36( $b36, $padlength );

DESCRIPTION

Top

This module converts to and from Base36 numbers (0..9 - A..Z)

It was created because of an article/challenge in "The Perl Review"

METHODS

Top

encode_base36( $number, [$padlength] )

Accepts a unsigned int and returns a Base36 string representation of the number. optionally zero-padded to $padlength.

decode_base36( $b36 )

Accepts a base36 string and returns a Base10 string representation of the number.

AUTHOR

Top

Rune Henssel <perl@henssel.dk>

MAINTAINER

Top

Brian Cassidy <bricas@cpan.org>

COPYRIGHT AND LICENSE

Top


Math-Base36 documentation Contained in the Math-Base36 distribution.

package Math::Base36;

use strict;
use warnings;

use base qw( Exporter );

use Math::BigInt ();

our %EXPORT_TAGS = ( 'all' => [ qw(encode_base36 decode_base36) ] );
our @EXPORT_OK = ( @{ $EXPORT_TAGS{ 'all' } } );

our $VERSION = '0.09';

sub decode_base36 {
    my $base36 = uc( shift );
    die 'Invalid base36 number' if $base36 =~ m{[^0-9A-Z]};

    my ( $result, $digit ) = ( 0, 0 );
    for my $char ( split( //, reverse $base36 ) ) {
        my $value = $char =~ m{\d} ? $char : ord( $char ) - 55;
        $result += $value * Math::BigInt->new( 36 )->bpow( $digit++ );
    }

    return $result;
}

sub encode_base36 {
    my ( $number, $padlength ) = @_;
    $padlength ||= 1;

    die 'Invalid base10 number'  if $number    =~ m{\D};
    die 'Invalid padding length' if $padlength =~ m{\D};

    my $result = '';
    while ( $number ) {
        my $remainder = $number % 36;
        $result .= $remainder <= 9 ? $remainder : chr( 55 + $remainder );
        $number = int $number / 36;
    }

    return '0' x ( $padlength - length $result ) . reverse( $result );
}

1;

__END__