Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Performing math operations on very large numbers in Perl

I have a case where some values in a data file have 64 bit wrap around which makes them very large, like, 18446744073709551608.

So I have to perform a subtraction from 2^64. I tried this using the simple

2^64 - 18446744073709551608

But I guess this number is too large and don't get the actual answer 8. What do I need to do to perform this substraction.

like image 311
sfactor Avatar asked Jan 06 '11 21:01

sfactor


2 Answers

Check out the bignum pragma:

use bignum;

print 2**64 - 18446744073709551608;

This should properly print 8.

like image 88
CanSpice Avatar answered Oct 13 '22 20:10

CanSpice


Note that bignum is just a layer that makes all constant numbers automatically Math::BigFloat or Math::BigInt objects. If you only want this for some numbers, you can either specify the use bignum; in a restricted scope, add no bignum; in places, or explicitly use Math::BigFloat->new('your constant') (or BigInt) to make particular numbers and the results of any operations involving them big.

like image 38
ysth Avatar answered Oct 13 '22 22:10

ysth