gargsan has asked for the wisdom of the Perl Monks concerning the following question:

Hi, How do i convert a big hex number to a bigint or bigfloat number, with the code below the hex function is overflowing

thanks
----------------------------------

$x= "0x0081def509be"; use Math::BigInt; $d = Math::BigInt->new(hex($x)); print $d , "\n";

Added code tags 2002-02-13 - dvergin

Replies are listed 'Best First'.
Re: Convert Hex to BigInt
by I0 (Priest) on Feb 13, 2002 at 23:18 UTC
    $x= "0x0081def509be"; use Math::BigInt; sub bighex{ my $x = shift; return Math::BigInt->new(hex($x)) if 8 > length $x; return (bighex(substr $x,0,-4)<<16) + hex substr($x,-4); } $d = bighex($x); print "$d\n";
      Thanks
Re: Convert Hex to BigInt
by belg4mit (Prior) on Feb 13, 2002 at 23:08 UTC

    Try this

    use Math::BigInt; $d = Math::BigInt->new(0); foreach my $h (split'','0x0081def509be'){ #UPDATE: Doh! Thinking base 10, this now # agrees with IO's result. It also # handles arbitrarily large hex values. # $d = Math::BigInt->new($d->bmul(10)); $d = Math::BigInt->new($d->bmul(16)); $d = Math::BigInt->new($d->badd(hex($h))); printf " :: %i : $d \n", hex($h); } print $d, "\n";
    Though we shouldn't have to make all those new calls in the loop. Even according to the documentation, which says the methods return objects. Oh well, it seems to work. Perhaps you could suggest they support new with a hex value, as that does not seem wholly unreasonable.

    --
    perl -pe "s/\b;([st])/'\1/mg"