I have to convert big numbers in Perl from decimal to binary and the other way around.
An example number of that length:
Dec: 76982379919017706648824420266
Bin: 111110001011111001010101000010011001000010101111001110000000000000000000000000000000000000000000
I found two functions:
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)));
}
But, both of them seem to stop working with big numbers.
Output of
bin2dec(111110001011111001010101000010011001000010101111001110000000000000000000000000000000000000000000)
is 1543163
and output of
dec2bin(76982379919017706422040262422)
is 11111111111111111111111111111111
Is there a proper way of doing it with such big numbers?
You can use Math::BigInt. Please note, that input to these functions should be strings.
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";
Output is:
Dec: 76982379919017710405206147072
Bin: 111110001011111001010101000010011001000010101111001101001001010101100110001100111001011110101010
Perl provides built-in bignum facilities. Turn them on with use bignum;. Your conversion functions would look like this:
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");
Caveat
There is no correspondence between the binary and the decimal number that you provide. I have not checked whether this is a flawof the bigint library or not.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With