我想在perl中做类似的事情:
@digits = ("1", "2", ..., "a", ... "z", ... ); ## a list of characters
$num = 1033;
convert_to_base($num, @digits);
现在,$num
将被转换为字符串,所使用的数字来自数字(因此基数为 $#digits + 1
)。
这可以通过迭代 $num
来完成,取 $num 相对于 $#digits
的模,然后除以直到达到 0,但我想知道是否有任何内置函数在 perl 中做到这一点(或者一个快速函数可以在 perl 中做到这一点)。
按照 choroba 对问题的评论中的建议使用 Math::Base::Convert :
#!/usr/bin/perl
use Math::Base::Convert "cnv";
my $num = 1033;
printf "%b", $num; # binary: 10000001001
printf "%o", $num; # octal: 2011
printf "%d", $num; # decimal: 1033
printf "%x", $num; # hexadecimal: 409
print cnv($num, 10, b64); # base64*: G9 (*: 0-9, A-Z, a-z, ., _)
print cnv($num, 10, b85); # base85*: CD (*: from RFC 1924)
print cnv($num, 10, ascii); # base96: *s
请注意,如果您需要将其解释为字符串,则可能需要执行
例如 printf "%s", "" . cnv($num, 10, b85);
正如@Adam Katz在他的回答中提到的,方法是使用Math::Base::Convert。但是,您的问题是关于使用任意基数。CPAN pod 不太清楚如何做到这一点,但它实际上就像
:use strict;
use Math::Base::Convert; # https://metacpan.org/pod/Math::Base::Convert
my $arb_enc = ['0'..'9', 'B'..'D', 'F'..'H', 'j'..'n', 'p'..'t', 'v'..'z', '*', '~'] ;
# ^^^^ note this is a array ref, which you can build with whatever characters you want
my $d_arbenc = new Math::Base::Convert('10', $arb_enc); # from decimal
my $arbenc_d = new Math::Base::Convert( $arb_enc, '10'); # to decimal
# test it like this:
foreach ( "1", "123", 62, 64, 255, 65535, 100, 10000, 1000000 ) {
my $status = eval { $d_arbenc->cnv($_) }; # if error, $status will be empty, and error message will be in $@
print "d_arbenc [$_] = [$status]n";
}
foreach ( "BD3F", "jjjnnnppp", "333", "bad string" ) {
my $status = eval { $arbenc_d->cnv($_) }; # if error, $status will be empty, and error message will be in $@
print "arbenc_d [$_] = [$status]n";
}