forked from t4sk/hello-foundry
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBit.sol
49 lines (48 loc) · 1.05 KB
/
Bit.sol
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.18;
contract Bit {
// Find most significant bit using binary search
function mostSignificantBit(uint256 x)
external
pure
returns (uint256 msb)
{
// x >= 2 ** 128
if (x >= 0x100000000000000000000000000000000) {
x >>= 128;
msb += 128;
}
// x >= 2 ** 64
if (x >= 0x10000000000000000) {
x >>= 64;
msb += 64;
}
// x >= 2 ** 32
if (x >= 0x100000000) {
x >>= 32;
msb += 32;
}
// x >= 2 ** 16
if (x >= 0x10000) {
x >>= 16;
msb += 16;
}
// x >= 2 ** 8
if (x >= 0x100) {
x >>= 8;
msb += 8;
}
// x >= 2 ** 4
if (x >= 0x10) {
x >>= 4;
msb += 4;
}
// x >= 2 ** 2
if (x >= 0x4) {
x >>= 2;
msb += 2;
}
// x >= 2 ** 1
if (x >= 0x2) msb += 1;
}
}