Skip to content

Perl’s arithmetic

Just descovered, the following code working incorrectly under perl 5.8.0, but works fine under perl 5.8.5:


sub StrToNum {
    my ($Str, $Check, $Magic) = @_;
    my $len = length($Str);

    for (my $i = 0; $i < $len; $i++) {
        $Check *= $Magic;
        $Check &= 0xFFFFFFFF;
        $Check += ord(substr($Str, $i, 1));
    }
    return $Check;
}

Working solution for perl 5.8.0:


sub StrToNum {
    my ($Str, $pCheck, $pMagic) = @_;
    my $len = length($Str);
    $Check = Math::BigInt->new($pCheck);
    $Magic = Math::BigInt->new($pMagic);

    for (my $i = 0; $i < $len; $i++) {
        $Check *= $Magic;
        $Check &= 0xFFFFFFFF;
        $Check += ord(substr($Str, $i, 1));
    }
    return $Check;
}

Leave a Reply

Your email address will not be published.