Skip to content

Core\BigInt::ofUint

Builds a Core\BigInt from a plain uint.

A uint is a whole number that is never negative, between 0 and 18446744073709551615. The upper half of that range is larger than any int, so Core\BigInt::of cannot be given those numbers at all. ofUint takes the whole range, and every value converts exactly.

Use it for the numbers your program already has as a uint: a length, a count of bytes, an identifier, a value that came out of a bit shift. Once the number is a Core\BigInt it can grow past the uint range as well, which is what a total of many counts does.

For a number that may be negative, use Core\BigInt::of. For one your program has as text, use Core\BigInt::parse.

Parameters

  • $valueuintThe uint to convert. Every uint converts exactly.

Return value

Returns Core\BigInt. A BigInt equal to $value.

Examples

Building one from a uint

<?nvs
// Shows how a program turns a plain `uint` into a `Core\BigInt`.
// `ofUint` takes any `uint`. This prints 4500.
echo Core\BigInt::ofUint(4500), "\n";
// Zero works the same way. This prints 0.
echo Core\BigInt::ofUint(0), "\n";
// The largest `uint` there is converts exactly. This prints
// 18446744073709551615.
echo Core\BigInt::ofUint(18446744073709551615), "\n";
// The number is never negative, so this prints 1 for every value but zero.
echo Core\BigInt::ofUint(18446744073709551615)->sign(), "\n";
Output
4500
0
18446744073709551615
1

The numbers an int cannot hold

<?nvs
// Shows the half of the `uint` range that no `int` can hold. `ofUint` is the
// way in for those numbers.
uint $identifier = 12000000000000000000;
// The number is larger than the largest `int`, which is 9223372036854775807.
// As a `Core\BigInt` it is exact, and this prints 12000000000000000000.
var $wide = Core\BigInt::ofUint($identifier);
echo $wide, "\n";
// Reading it back as a `uint` gives the number you started with. This prints
// 12000000000000000000.
echo $wide->toUint(), "\n";
// Reading it back as an `int` throws an error, because it does not fit. This
// prints "outside the int range".
try {
echo $wide->toInt(), "\n";
} catch (ArithmeticError $tooLarge) {
echo "outside the int range\n";
}
Output
12000000000000000000
12000000000000000000
outside the int range

Adding up counts that pass the uint range

<?nvs
// Shows a total that stays exact. Each count fits a `uint`, and the total of
// them does not.
class Traffic
{
// Returns the total of $counts, which may be larger than any `uint`.
public static function total(array<uint> $counts): Core\BigInt
{
var $total = Core\BigInt::of(0);
foreach ($counts as uint $count) {
$total = $total->plus(Core\BigInt::ofUint($count));
}
return $total;
}
}
array<uint> $counts = [
18000000000000000000,
18000000000000000000,
446744073709551615,
];
// The three counts together are larger than any `uint`. The total is exact,
// and this prints 36446744073709551615.
echo Traffic::total($counts), "\n";
Output
36446744073709551615