如何在perl中将一个数转换为任意基数?

nvbavucw  于 2022-11-15  发布在  Perl
关注(0)|答案(2)|浏览(156)

我想在perl中做一些类似下面的事情:

@digits = ("1", "2", ..., "a", ... "z", ... ); ## a list of characters
$num = 1033;
convert_to_base($num, @digits);

现在,$num将被转换为一个字符串,其中使用的数字来自digits(因此基数为$#digits + 1)。
它可以通过在$num上迭代来完成,取$num对$#digits的模,然后除以0,但是我想知道在perl中是否有内置函数可以完成这个任务(或者在perl中有一个快速函数可以完成这个任务)。

hrirmatl

hrirmatl1#

使用Math::Base::Convert,如choroba对问题的注解中所建议的:

#!/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);

5hcedyr0

5hcedyr02#

正如@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";    
    }

相关问题