Alphaneo
Alphaneo

Reputation: 12539

How can I do 64-bit arithmetic in Perl?

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;

Upvotes: 12

Views: 12926

Answers (5)

wvdz
wvdz

Reputation: 16641

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

Eg.:

use bigint;
print 1 << 256;

will print:

115792089237316195423570985008687907853269984665640564039457584007913129639936

Upvotes: 0

Sinan &#220;n&#252;r
Sinan &#220;n&#252;r

Reputation: 118128

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...

Upvotes: 11

Znik
Znik

Reputation: 1136

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 .

Upvotes: 0

Greg Hewgill
Greg Hewgill

Reputation: 992955

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.

Upvotes: 5

Alan Haggai Alavi
Alan Haggai Alavi

Reputation: 74202

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

Upvotes: 14

Related Questions