Dr.Ruud said:
#!/usr/bin/perl
use strict; use warnings;
use constant Chars => ('0'..'9', 'A'..'Z', 'a'..'z');
use constant MaxBase => scalar Chars;
{ local ($,, $\) = ("\t", "\n");
for (my $i = 0; $i != 30; $i++) {
print $i, int2base($i, 16, 4);
}
}
sub int2base {
use integer;
my ($ret, $num, $base, $minlen) = ('', @_);
return undef if $num < 0
|| ($base ||= 10) < 2
|| MaxBase < $base
|| ($minlen ||= 1) < 1;
for (; $num; $num /= $base) {
$ret .= (Chars)[$num % $base];
}
return scalar reverse $ret . '0'x($minlen - length($ret));
}
I assume you left this as an excercise for the reader?
use constant Charstr => join '', Chars;
sub base2int {
use integer;
my ($ret, $num, $base) = (0, @_);
return if $num !~ /^[${\Charstr}]+$/o
|| ($base ||= 10) < 2
|| MaxBase < $base;
for( my $i = length($num)-1, my $c = 0; $i >= 0; --$i ) {
$ret += index(Charstr, substr($num, $i, 1)) * $base**$c++;
}
return $ret;
}