Skip to content

Instantly share code, notes, and snippets.

@atarpara
Created August 23, 2022 08:36
Show Gist options
  • Save atarpara/ab75e1f42bcea6ca271ad634bae97d21 to your computer and use it in GitHub Desktop.
Save atarpara/ab75e1f42bcea6ca271ad634bae97d21 to your computer and use it in GitHub Desktop.
pragma solidity ^0.8.4;
library LibBit {
function msbPosition(uint256 value) internal pure returns(uint8 position) {
assembly {
if gt(value,0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) {
value := shr(128,value)
position := add(128,position)
}
if gt(value,0xFFFFFFFFFFFFFFFF) {
value := shr(64,value)
position := add(64,position)
}
if gt(value,0xFFFFFFFF) {
value := shr(32,value)
position := add(32,position)
}
if gt(value,0xFFFF) {
value := shr(16,value)
position := add(16,position)
}
if gt(value,0xFF) {
value := shr(8,value)
position := add(8,position)
}
if gt(value,0xF) {
value := shr(4,value)
position := add(4,position)
}
if gt(value,0x03) {
value := shr(2,value)
position := add(2,position)
}
if gt(value,0x01){
value := shr(1,value)
position := add(1,position)
}
}
}
function lsbPosition(uint256 value) internal pure returns (uint8 position) {
assembly{
if iszero(iszero(value)){
for {} 1 {} {
if iszero(iszero(and(value,1))) {
break
}
position := add(position,1)
value := shr(1,value)
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment