perlkomodo

Perl: Adding two numbers, one of which is more than 32 bits


If I have

my $hex_str = "fffff00000000";

my $hex_val = hex($hex_str);

my $sum = $hex_val + 5;

$sum is what I expect - 0xfffff00000005

If I have

my $hex_str = "ffffff00000000";

my $hex_val = hex($hex_str);

my $sum = $hex_val + 5;

Komodo shows $sum being 0xffffff00000008

If I have

my $hex_str = "fffffff00000000";

my $hex_val = hex($hex_str);

my $sum = $hex_val + 5;

Komodo shows $sum being 0xfffffff00000000

Can someone explain to me why I get unexpected values in the second and third case?

>perl -V:use64bitint
use64bitint='define';

>perl -V:ivsize
ivsize='8';

>perl -V:archname
archname='MSWin32-x64-multi-thread';

Solution

  • You don't show the code you use to print $sum; that may be where the problem is, but I can't duplicate it. In any case, if you have warnings enabled, the call to hex() is going to give you a Hexadecimal number > 0xffffffff non-portable warning.

    You could do:

    use strict;
    use warnings;
    use Math::BigInt;
    
    my $hex_str = "ffffff00000000";
    my $hex_val = Math::BigInt->new("0x$hex_str");
    my $sum = $hex_val + 5;
    print $sum->as_hex, "\n";