gpt4 book ai didi

perl - 大数的十进制和二进制转换

转载 作者:行者123 更新时间:2023-12-01 11:34:14 43 4
gpt4 key购买 nike

我必须将 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

有没有合适的方法来处理这么大的数字?

最佳答案

您可以使用 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

关于perl - 大数的十进制和二进制转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29047084/

43 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com