DEV Community

RareSkills
RareSkills

Posted on • Originally published at rareskills.io

Uint256 max value

The maximum value of uint256 can be obtained with

type(uint256).max;

Enter fullscreen mode Exit fullscreen mode

Which is equal to 115792089237316195423570985008687907853269984665640564039457584007913129639935 (2²⁵⁶ - 1). But it's cleaner and safer to use type(uint256).max.
The same can be used for signed integer types

//57896044618658097711785492504343953926634992332820282019728792003956564819967
type(int256).max;

//-57896044618658097711785492504343953926634992332820282019728792003956564819968
type(int256).min;
Enter fullscreen mode Exit fullscreen mode

Hacky ways to get the uint256 maximum value

You could also specify it with hexadecimal, which would be a little cleaner than using the decimal representation, but still space consuming and error prone.

0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff

Enter fullscreen mode Exit fullscreen mode

That's exactly 64 'f's, don't get it wrong! The 64 is derived from 256 bits divided by 8 to get the number of bytes (32), and each maximum byte is represented in hex by 0xff.
Another ugly solution is to underflow the integer

function maximum() public pure returns(uint256) {
   unchecked { return uint256(0) - uint256(1); }
}
Enter fullscreen mode Exit fullscreen mode

The following code works properly, but it is deceptive and not recommended for use

function maxUint() public pure returns (uint256) {
    return 2**256 - 1;
}
Enter fullscreen mode Exit fullscreen mode

It returns the correct value, which you can verify with

assert(2**256 - 1 == type(uint256).max);
Enter fullscreen mode Exit fullscreen mode

If you write 2*256 as a constant in solidity, the code won't compile because the compiler recognized 2*256 is too large to fit in uint256. But if it is immediately followed by a "- 1", then the compiler recognized the result of the arithmetic is valid with the type.
It's better to just avoid all these gymnastics and just do type(uint256).max;

Learn more

If you are new to Solidity, see our learn solidity free for beginners course.
For intermediate and advanced developers, please see our expert solidity bootcamp.

Top comments (0)