I need to find the value (or position) of the most significant bit (MSB) of an integer in Swift.
Eg:
- Input number: 9
- Input as binary: 1001
- MS value as binary: 1000 -> (which is 8 in decimal)
- MS position as decimal: 3 (because
1<<3 == 1000
)
Many processors (Intel, AMD, ARM) have instructions for this. In c, these are exposed. Are these instructions similarly available in Swift through a library function, or would I need to implement some bit twiddling?
The value is more useful in my case.
If a position is returned, then the value can be easily derived by a single shift.
Conversely, computing position from value is not so easy unless a fast Hamming Weight / pop count function is available.