Is There a Biginteger Class in PHP

Is there a BigInteger class in PHP?

Hopefully helpfull links :

  • http://php.net/manual/en/ref.bc.php
  • http://php.net/manual/en/ref.gmp.php

EDIT: Math_BigInteger

Example from http://phpseclib.sourceforge.net/documentation/math.html :

Implements an arbitrary precision integer arithmetic library. Uses gmp or bcmath, if available, and an internal implementation, otherwise.

<?php
include('Math/BigInteger.php');

$a = new Math_BigInteger(2);
$b = new Math_BigInteger(3);

$c = $a->add($b);

echo $c->toString(); // outputs 5
?>

How to work with big numbers in PHP?

You can go for BCMath to work with big numbers.

Working with large numbers in PHP

For some reason, there are two standard libraries in PHP handling the arbitrary length/precision numbers: BC Math and GMP. I personally prefer GMP, as it's fresher and has richer API.

Based on GMP I've implemented Decimal2 class for storing and processing currency amounts (like USD 100.25). A lot of mod calculations there w/o any problems. Tested with very large numbers.

Random variable length bigint(8) number using PHP?

Short answer, gmp_random_range():

$from = 0;
$to = '18446744073709551615';
$random = gmp_random_range($from, $to);
var_dump($random, (string)$random);

E.g.:

object(GMP)#1 (1) {
["num"]=>
string(20) "10366718409313808674"
}
string(20) "10366718409313808674"

Additional digressions:

  • MySQL's BIGINT is an 8-byte integer, what means -263 to 263-1 if signed and 0 to 264-1 if unsigned.

  • PHP_INT_MAX is a 4-byte value in 32-bit builds but an 8-byte value in 64-bit builds. It's signed in either case.

So if you could safely assume 64-bit PHP and you wanted signed numbers then you'd be basically done with any random generation function. You could use random_int() if you're after cryptographically secure numbers or mt_rand() otherwise:

var_dump(random_int(0, PHP_INT_MAX));
var_dump(mt_rand(0, PHP_INT_MAX));

But you want unsigned values, thus you must switch to strings. Once there, an obvious approach is to generate two integers and concatenate them as strings—the tricky part is ensuring you don't overflow your range. As alternative, you can use the GMP arbitrary precision extension, which happily has a dedicated function.

P.S. You actually mention BIGINT(8). That 8 is nothing but the display size when printing from compliant clients, it doesn't represent the storage range and it isn't enforced by any mean. And since you clearly state you expect up to 20 digits, it's just misleading.

How do Divide a H U G E Number in PhP

BC Math can calculate with strings. I am guessing you want to have the remainer of the division only? Then bcmod would be your choice. Otherwise pick bcdiv.

Note: works only php 7.2+, before this functions cuts with int precision as well.



Related Topics



Leave a reply



Submit