Benjohn Benjohn - 4 months ago 23
Swift Question

Find most significant bit in Swift

I need to find the value (or position) of the most significant bit (MSB) of an integer in Swift.


  • 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.

Answer Source

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 bits are numbered starting at 1, the least significant bit.