Benjohn - 6 months ago 32

Swift Question

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**1000 -> (which is 8 in decimal)*value*as binary:**MS**3 (because*position*as decimal:)`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.