-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path44MostSignificantBitFunction.sol
More file actions
54 lines (50 loc) · 1.28 KB
/
Copy path44MostSignificantBitFunction.sol
File metadata and controls
54 lines (50 loc) · 1.28 KB
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
50
51
52
53
54
/*
# Bitwise Operators
Most significant bit in assembly
*/
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;
contract MostSignificantBitAssembly {
function mostSignificantBit(uint x) external pure returns (uint msb) {
assembly {
let f := shl(7, gt(x, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF))
x := shr(f, x)
// or can be replaced with add
msb := or(msb, f)
}
assembly {
let f := shl(6, gt(x, 0xFFFFFFFFFFFFFFFF))
x := shr(f, x)
msb := or(msb, f)
}
assembly {
let f := shl(5, gt(x, 0xFFFFFFFF))
x := shr(f, x)
msb := or(msb, f)
}
assembly {
let f := shl(4, gt(x, 0xFFFF))
x := shr(f, x)
msb := or(msb, f)
}
assembly {
let f := shl(3, gt(x, 0xFF))
x := shr(f, x)
msb := or(msb, f)
}
assembly {
let f := shl(2, gt(x, 0xF))
x := shr(f, x)
msb := or(msb, f)
}
assembly {
let f := shl(1, gt(x, 0x3))
x := shr(f, x)
msb := or(msb, f)
}
assembly {
let f := gt(x, 0x1)
msb := or(msb, f)
}
}
}