NumberLib

Git Source

Number

Library for compact representation of uint256 numbers.

  • Number is stored using mantissa and exponent, each occupying 8 bits.
  • Numbers under 2**8 are stored as mantissa with exponent = 0xFF.
  • Numbers at least 2**8 are approximated as (256 + mantissa) << exponent
  • 0 <= mantissa < 256
  • 0 <= exponent <= 247 (256 * 2**248 doesn't fit into uint256)

Number stack layout (from highest bits to lowest)

PositionFieldTypeBytes
(002..001]mantissauint81
(001..000]exponentuint81

State Variables

SHIFT_MANTISSA

Amount of bits to shift to mantissa field

uint16 private constant SHIFT_MANTISSA = 8;

BWAD_SHIFT

For bwad math (binary wad) we use 2**64 as "wad" unit.

We are using not using 10**18 as wad, because it is not stored precisely in NumberLib.

uint256 internal constant BWAD_SHIFT = 64;

BWAD

uint256 internal constant BWAD = 1 << BWAD_SHIFT;

PER_MILLE_SHIFT

~0.1% in bwad units.

uint256 internal constant PER_MILLE_SHIFT = BWAD_SHIFT - 10;

PER_MILLE

uint256 internal constant PER_MILLE = 1 << PER_MILLE_SHIFT;

Functions

compress

Compresses uint256 number into 16 bits.

function compress(uint256 value) internal pure returns (Number);

decompress

Decompresses 16 bits number into uint256.

The outcome is an approximation of the original number: (value - value / 256) < number <= value.

function decompress(Number number) internal pure returns (uint256 value);

mostSignificantBit

Returns the most significant bit of x https://solidity-by-example.org/bitwise/

function mostSignificantBit(uint256 x) internal pure returns (uint256 msb);

_encode

Wraps (mantissa, exponent) pair into Number.

function _encode(uint8 mantissa, uint8 exponent) private pure returns (Number);