34 lines
1.0 KiB
Solidity
34 lines
1.0 KiB
Solidity
pragma solidity =0.5.16;
|
||
|
||
/**
|
||
* @title UQ112x112 定点数运算库
|
||
* @notice 处理二进制定点数的库 (Q数字格式)
|
||
* @dev 参考: https://en.wikipedia.org/wiki/Q_(number_format)
|
||
* @dev 范围: [0, 2**112 - 1],精度: 1 / 2**112
|
||
*/
|
||
library UQ112x112 {
|
||
// Q112常量,表示2^112,用于编码和解码
|
||
uint224 constant Q112 = 2**112;
|
||
|
||
/**
|
||
* @notice 将uint112编码为UQ112x112格式
|
||
* @param y 要编码的uint112数值
|
||
* @return z 编码后的UQ112x112数值
|
||
* @dev 乘以Q112进行编码,永不溢出
|
||
*/
|
||
function encode(uint112 y) internal pure returns (uint224 z) {
|
||
z = uint224(y) * Q112; // 永不溢出
|
||
}
|
||
|
||
/**
|
||
* @notice UQ112x112除以uint112,返回UQ112x112
|
||
* @param x UQ112x112格式的被除数
|
||
* @param y uint112格式的除数
|
||
* @return z UQ112x112格式的商
|
||
* @dev 用于价格计算,保持定点数精度
|
||
*/
|
||
function uqdiv(uint224 x, uint112 y) internal pure returns (uint224 z) {
|
||
z = x / uint224(y);
|
||
}
|
||
}
|