Perl十进制和二进制转换与大数字

时间:2015-03-14 08:40:25

标签: perl binary type-conversion decimal

我必须将perl中的大数字从十进制转换为二进制,反之亦然。

该长度的示例数:

Dec: 76982379919017706648824420266
Bin: 111110001011111001010101000010011001000010101111001110000000000000000000000000000000000000000000

在论坛中,我发现了两个功能:

sub dec2bin {
    my $str = unpack("B32", pack("N", shift));
    $str =~ s/^0+(?=\d)//;   # otherwise you'll get leading zeros
    return $str;
}
sub bin2dec {
    return unpack("N", pack("B32", substr("0" x 32 . shift, -32)));
}

但是,当它达到如此大的数字时,它们似乎都停止了工作......

Output of
bin2dec(111110001011111001010101000010011001000010101111001110000000000000000000000000000000000000000000)
is 1543163 
and output of
dec2bin(76982379919017706422040262422)
is 11111111111111111111111111111111

有这么大的数字吗? 提前谢谢!

3 个答案:

答案 0 :(得分:3)

您可以使用Math::BigInt。请注意,这些函数的输入应该是字符串。

use Math::BigInt;

sub bin2dec {
  my $bin = shift;
  return Math::BigInt->new("0b$bin");
}

sub dec2bin {
  my $dec = shift;
  my $i = Math::BigInt->new($dec);
  return substr($i->as_bin(), 2);
}

print "Dec: " . bin2dec("111110001011111001010101000010011001000010101111001110000000000000000000000000000000000000000000") . "\n";
print "Bin: " . dec2bin("76982379919017706648824420266") . "\n";

输出是:

Dec: 76982379919017710405206147072
Bin: 111110001011111001010101000010011001000010101111001101001001010101100110001100111001011110101010

答案 1 :(得分:1)

Perl提供built-in bignum facilities。用use bignum;打开它们。您的转换函数如下所示:

use bignum;
my ($b_orig, $d_orig, $b, $d);

$d_orig = 76982379919017706648824420266;
$b_orig = '111110001011111001010101000010011001000010101111001110000000000000000000000000000000000000000000';

print ("dec($b_orig) [orig] = $d_orig;\n");
print ("dec($b_orig) [comp] = " . Math::BigInt->from_bin($b_orig) . ";\n");
print ("bin($d_orig) [orig] = $b_orig;\n");
print ("bin($d_orig) [comp] = ".substr(Math::BigInt->new($d_orig)->as_bin(), 2).";\n");

<强> 买者

您提供的二进制数和十进制数之间没有对应关系。我还没有检查这是否是bigint库的缺陷。

答案 2 :(得分:1)

Perl的bigint为大整数提供透明支持:

perl -Mbigint -E 'say oct "0b111110001011111001010101000010011001000010101111001110000000000000000000000000000000000000000000"'
76982379919017710405206147072

您无需编写自己的转换例程。 oct会为您转换。