Skip to content

Instantly share code, notes, and snippets.

@tsuchm
Created March 8, 2018 01:48
Show Gist options
  • Save tsuchm/0c32dcefeae6d3859acc0bef94283179 to your computer and use it in GitHub Desktop.
Save tsuchm/0c32dcefeae6d3859acc0bef94283179 to your computer and use it in GitHub Desktop.
Perl encode/decoder of base62 format
use constant PRIMITIVES => join( '', 0 .. 9, 'a' .. 'z', 'A' .. 'Z' );
sub encode_base62 {
my( $num ) = @_;
my @c;
do {
push( @c, substr( PRIMITIVES, $num % length(PRIMITIVES), 1 ) );
$num = int( $num / length(PRIMITIVES) );
} while( $num );
join( '', reverse @c );
}
sub decode_base62 {
my( $str ) = @_;
my $num = 0;
my $place = 1;
for my $c ( reverse split( //, $str ) ){
$num += index(PRIMITIVES, $c) * $place;
$place *= length(PRIMITIVES);
}
$num;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment