Mathai Mathai - 26 days ago 5
Perl Question

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;


$sum
is
0xffffff00000008


If I have

my $hex_str = "fffffff00000000";

my $hex_val = hex($hex_str);

my $sum = $hex_val + 5;


$sum
is
0xfffffff00000000


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

My Perl seems to be 64 bit

use Config;
print $Config{use64bitint};


prints
define

Answer

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";
Comments