11

I am a perl newbie,

Can I simply use 64-bit arithmetic in Perl?

For example

$operand1 = 0xFFFFFFFFFFFF;   # 48 bit value
$operand2 = 0xFFFFFFFFFFFF;   # 48 bit value

$Result = $operand1 * $operand2;
  • I am basically looking for a replacement for the int64_t in perl.
  • Is there any way to mention, if the variable is signed or unsigned?
Alois Mahdal
  • 10,763
  • 7
  • 51
  • 69
Alphaneo
  • 12,079
  • 22
  • 71
  • 89

5 Answers5

14

Yes, however you need to have Perl compiled with 64-bit support.

Alan Haggai Alavi
  • 72,802
  • 19
  • 102
  • 127
  • 7
    "use bigint" will ensure that it always works. (If you want absolute speed, you picked the wrong programming language.) – jrockway Dec 08 '09 at 02:42
  • 4
    Perl is often used in bioinformatics and other fields requiring high-performance. If your numbers are sure to fit within 64 bits, then this answer will create better performing code. Just make sure to use a recent version of Perl, and you may want to compile it yourself. "64-bit support is now considered to be mature" http://dev.perl.org/perl5/news/2002/07/18/580ann/ – Paul Dec 08 '09 at 02:57
  • 8
    Even with 64 bit support, you'd need a `use integer;` to avoid getting a (rounded) floating point result and instead get a (high-bits truncated) integer result. – ysth Dec 08 '09 at 03:37
11

See bigint:

Transparent BigInteger support for Perl...

All operators (including basic math operations) except the range operator .. are overloaded. Integer constants are created as proper BigInts.

Floating point constants are truncated to integer. All parts and results of expressions are also truncated.

Unlike integer, this pragma creates integer constants that are only limited in their size by the available memory and CPU time...

gnat
  • 6,213
  • 108
  • 53
  • 73
Sinan Ünür
  • 116,958
  • 15
  • 196
  • 339
5

Yes, Perl automatically handles large integer arithmetic for you. However, Perl does not offer a distinction between signed and unsigned types (there's no need, since there are not fixed bounds on large integer range).

The perlnumber manual page has more information about the different numeric formats supported by Perl.

Greg Hewgill
  • 951,095
  • 183
  • 1,149
  • 1,285
0

Be aware, 64bit arithmetic in Perl is one, but what it is displayed by sprintf %d %u and %s, is second. Current perl version supports 64bits without problems, but sprintf %d format not, %b likewise .

Znik
  • 1,047
  • 12
  • 17
0

use bigint will make Perl handle arbitrary size integers correctly without integer overflow.

Eg.:

use bigint;
print 1 << 256;

will print:

115792089237316195423570985008687907853269984665640564039457584007913129639936
wvdz
  • 16,251
  • 4
  • 53
  • 90