1

I have a scenario where I take 2 very big binary strings (having 100 characters) and I need to add them.

The issue is that I am getting the answer in the form 2.000xxxxxxxxxxe+2, whereas I need the precise answer, as another 100 character long string.

chomp($str1=<STDIN>);
chomp($str2=<STDIN>);
print "Str 1 is $str1\n";
print "Str 2 is $str2\n";
$t = $str1 + $str2;
print "Sum is $t\n";

Sample Input

1001101111101011011100101100100110111011111011000100111100111110111101011011011100111001100011111010
1001101111101011011100101100100110111011111011000100111100111110111101011011011100111001100011111010

Sample Output
Str1 is

1001101111101011011100101100100110111011111011000100111100111110111101011011011100111001100011111010      

Str2 is

1001101111101011011100101100100110111011111011000100111100111110111101011011011100111001100011111010

Sum is

2.0022022220202e+099
tripleee
  • 175,061
  • 34
  • 275
  • 318
Saurabh Shrivastava
  • 1,394
  • 4
  • 21
  • 50

2 Answers2

4

As already suggested, you can use Math::BigInt core module,

use Math::BigInt;

# chomp($str1=<STDIN>);
# chomp($str2=<STDIN>);
# print "Str 1 is $str1\n";
# print "Str 2 is $str2\n";

my $t = Math::BigInt->new("0b$str1") + Math::BigInt->new("0b$str2");

print $t->as_bin;
mpapec
  • 50,217
  • 8
  • 67
  • 127
0

In order to perform arithmetic on your strings, Perl converts them to floating-point numbers, which are inherently imprecise. If you want to avoid that, use Math::BigInt as already suggested ... or roll your own.

######## WARNING/GUARANTEE: This is practically certain to be
# slower, buggier, less portable, and less secure than Math::BigInt.
# In fact, I planted a security hole just to prove a point.  Enjoy.

use strict;
use warnings;

sub addition {
    my ($int1, $int2) = @_;
    my @int1 = reverse split //, $int1;
    my @int2 = reverse split //, $int2;
    my $len = scalar(@int1>@int2 ? @int1 : @int2);

    my @result;
    my $carry = 0;
    for (my $i=0; $i < $len; ++$i)
    {
        $int1[$i] |= 0;
        $int2[$i] |= 0;
        my $sum = $carry + $int1[$i] + $int2[$i];
        if ($sum >= 10)
        {
            $carry = int($sum / 10);
            $sum %= 10;
        }
        push @result, $sum;
    }
    push @result, $carry if $carry;
    return join ('', reverse @result);
}
Community
  • 1
  • 1
tripleee
  • 175,061
  • 34
  • 275
  • 318