Skip to content

Instantly share code, notes, and snippets.

@PaulRBerg
Last active November 29, 2022 16:47
Show Gist options
  • Save PaulRBerg/f932f8693f2733e30c4d479e8e980948 to your computer and use it in GitHub Desktop.
Save PaulRBerg/f932f8693f2733e30c4d479e8e980948 to your computer and use it in GitHub Desktop.
High-level Solidity function that calculates the most significant bit
/// @notice Finds the zero-based index of the first 1 in the binary representation of x.
/// @dev See the note on msb in the "Find First Set" Wikipedia article https://en.wikipedia.org/wiki/Find_first_set
/// @param x The uint256 number for which to find the index of the most significant bit.
/// @return result The index of the most significant bit as an uint256.
function msb(uint256 x) pure returns (uint256 result) {
unchecked {
if (x >= 2 ** 128) {
x >>= 128;
result += 128;
}
if (x >= 2 ** 64) {
x >>= 64;
result += 64;
}
if (x >= 2 ** 32) {
x >>= 32;
result += 32;
}
if (x >= 2 ** 16) {
x >>= 16;
result += 16;
}
if (x >= 2 ** 8) {
x >>= 8;
result += 8;
}
if (x >= 2 ** 4) {
x >>= 4;
result += 4;
}
if (x >= 2 ** 2) {
x >>= 2;
result += 2;
}
// No need to shift x any more.
if (x >= 2 ** 1) {
result += 1;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment