Created
March 8, 2018 01:48
-
-
Save tsuchm/0c32dcefeae6d3859acc0bef94283179 to your computer and use it in GitHub Desktop.
Perl encode/decoder of base62 format
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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