Find most significant bit in Swift
bit-manipulation, swift
Solution
You can use the `flsl()` function ("find last set bit, long"):
let x = 9
let p = flsl(x)
print(p) // 4
The result is `4` because `flsl()` and the related functions number the bits starting at 1, the least significant bit.
On Intel platforms you can use the `_bit_scan_reverse` intrinsic, in my test in a macOS application this translated to a `BSR` instruction.
import _Builtin_intrinsics.intel
let x: Int32 = 9
let p = _bit_scan_reverse(x)
print(p) // 3
Problem
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.