github.com/0xPolygon/supernets2-node@v0.0.0-20230711153321-2fe574524eaa/test/contracts/uniswap/v2/BitMath.sol (about)

     1  // SPDX-License-Identifier: GPL-3.0-or-later
     2  pragma solidity >=0.5.0;
     3  
     4  library BitMath {
     5      // returns the 0 indexed position of the most significant bit of the input x
     6      // s.t. x >= 2**msb and x < 2**(msb+1)
     7      function mostSignificantBit(uint256 x) internal pure returns (uint8 r) {
     8          require(x > 0, 'BitMath::mostSignificantBit: zero');
     9  
    10          if (x >= 0x100000000000000000000000000000000) {
    11              x >>= 128;
    12              r += 128;
    13          }
    14          if (x >= 0x10000000000000000) {
    15              x >>= 64;
    16              r += 64;
    17          }
    18          if (x >= 0x100000000) {
    19              x >>= 32;
    20              r += 32;
    21          }
    22          if (x >= 0x10000) {
    23              x >>= 16;
    24              r += 16;
    25          }
    26          if (x >= 0x100) {
    27              x >>= 8;
    28              r += 8;
    29          }
    30          if (x >= 0x10) {
    31              x >>= 4;
    32              r += 4;
    33          }
    34          if (x >= 0x4) {
    35              x >>= 2;
    36              r += 2;
    37          }
    38          if (x >= 0x2) r += 1;
    39      }
    40  
    41      // returns the 0 indexed position of the least significant bit of the input x
    42      // s.t. (x & 2**lsb) != 0 and (x & (2**(lsb) - 1)) == 0)
    43      // i.e. the bit at the index is set and the mask of all lower bits is 0
    44      function leastSignificantBit(uint256 x) internal pure returns (uint8 r) {
    45          require(x > 0, 'BitMath::leastSignificantBit: zero');
    46  
    47          r = 255;
    48          if (x & uint128(-1) > 0) {
    49              r -= 128;
    50          } else {
    51              x >>= 128;
    52          }
    53          if (x & uint64(-1) > 0) {
    54              r -= 64;
    55          } else {
    56              x >>= 64;
    57          }
    58          if (x & uint32(-1) > 0) {
    59              r -= 32;
    60          } else {
    61              x >>= 32;
    62          }
    63          if (x & uint16(-1) > 0) {
    64              r -= 16;
    65          } else {
    66              x >>= 16;
    67          }
    68          if (x & uint8(-1) > 0) {
    69              r -= 8;
    70          } else {
    71              x >>= 8;
    72          }
    73          if (x & 0xf > 0) {
    74              r -= 4;
    75          } else {
    76              x >>= 4;
    77          }
    78          if (x & 0x3 > 0) {
    79              r -= 2;
    80          } else {
    81              x >>= 2;
    82          }
    83          if (x & 0x1 > 0) r -= 1;
    84      }
    85  }