Reputation: 94465
I want to write a perl script to parse text files with a lot of 64-bit integers in it. All integers are written in hex.
I need to
<
, =
, >
)I need to use 32-bit perl and I can't use any CPAN/external module (the script must be portable).
PS my perl is 5.8 (and this is minimal version which will be used for the script)
PPS bignum/ bigint errors:
$ perl -e 'use bignum; $_=hex("0x0000123412345678")'
Integer overflow in hexadecimal number at -e line 1.
$ perl -e 'use bigint; $_=hex("0x0000123412345678")'
Integer overflow in hexadecimal number at -e line 1.
PPPS: no from_hex
here.
$ perl -e 'use Math::BigInt; $_=Math::BigInt->from_hex("0x0000123412345678");'
Can't locate object method "from_hex" via package "Math::BigInt" at -e line 1.
And no qw/hex/
:
$ perl -e 'use bigint qw/hex/; $_=hex("0x0000123412345678")'
unknown option hex at /usr/lib/perl5/5.8/bigint.pm line...
PPPPS: but new() works:
$ perl -e 'use Math::BigInt; $_=Math::BigInt->new("0x0000123412345678"); print $_->as_hex(),"\n";'
0x123412345678
Upvotes: 3
Views: 5597
Reputation: 386676
Math::Int64 gives access to native signed and unsigned 64-bit numbers. This is surely faster than possible alternative Math::BigInt.
It has hex conversion routines, and it overloads comparison and arithmetic operators, so it can do everything you asked for.
use Math::Int64 qw( hex_to_uint64 uint64_to_hex );
my $n1 = hex_to_uint64("200000000");
my $n2 = hex_to_uint64("300000000");
printf("n1 is %s equal to n2\n", $n1 == $n2 ? "" : "not");
printf("n1 is %s less than n2\n", $n1 < $n2 ? "" : "not");
printf("n1 is %s greater than n2\n", $n1 > $n2 ? "" : "not");
printf("0x%016s", uint64_to_hex($n2 - $n1));
Output:
n1 is not equal to n2
n1 is less than n2
n1 is not greater than n2
0x0000000100000000
The use of CPAN or lack thereof doesn't effect the portability of the script.
Upvotes: 4
Reputation: 40152
The core pragma bigint will let you transparently work with integers larger than your system can support. There are associated functions in the Math::BigInt core library to convert from and to a hex representation.
Upvotes: 10