Created
August 24, 2022 05:34
-
-
Save atarpara/79aacc2aeeab5fcec555a10d13177505 to your computer and use it in GitHub Desktop.
Most Significant Bit Index
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
pragma solidity ^0.8.4; | |
library LibBit { | |
function msbPosition(uint256 value) internal pure returns(uint8 position) { | |
assembly { | |
// value > 2*128 - 1 | |
if gt(value,0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) { | |
value := shr(128,value) | |
position := add(128,position) | |
} | |
// value > 2*64 - 1 | |
if gt(value,0xFFFFFFFFFFFFFFFF) { | |
value := shr(64,value) | |
position := add(64,position) | |
} | |
// value > 2*32 - 1 | |
if gt(value,0xFFFFFFFF) { | |
value := shr(32,value) | |
position := add(32,position) | |
} | |
// value > 2*16 - 1 | |
if gt(value,0xFFFF) { | |
value := shr(16,value) | |
position := add(16,position) | |
} | |
// value > 2*8 - 1 | |
if gt(value,0xFF) { | |
value := shr(8,value) | |
position := add(8,position) | |
} | |
// value > 2*4 - 1 | |
if gt(value,0xF) { | |
value := shr(4,value) | |
position := add(4,position) | |
} | |
// value > 2*2 - 1 | |
if gt(value,0x03) { | |
value := shr(2,value) | |
position := add(2,position) | |
} | |
// value > 2*1 - 1 | |
if gt(value,0x01){ | |
value := shr(1,value) | |
position := add(1,position) | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment