How do you find the position of the most significant bit (MSB) of an unsigned integer in Swift

1 Answer

0 votes
import Foundation

/// Returns the zero-based position of the most significant set bit (MSB)
/// in an unsigned 32-bit integer.
///
/// Examples:
///   1  -> 0
///   2  -> 1
///   8  -> 3
///   15 -> 3
///
/// - Parameter value:
///   Unsigned integer to examine.
/// - Returns:
///   The zero-based position of the highest set bit,
///   or `nil` if the value is 0.
func msbPosition(of value: UInt32) -> Int? {
    guard value != 0 else {
        return nil
    }

    return UInt32.bitWidth - 1 - value.leadingZeroBitCount
}

func main() {
    let testValues: [UInt32] = [
        0,
        1,
        2,
        8,
        15,
        0x1234,
        0x8000_0000
    ]

    for value in testValues {
        if let position = msbPosition(of: value) {
            print("Value: \(value), MSB position: \(position)")
        } else {
            print("Value: \(value), no bits are set")
        }
    }
}

main()


/*
run:

Value: 0, no bits are set
Value: 1, MSB position: 0
Value: 2, MSB position: 1
Value: 8, MSB position: 3
Value: 15, MSB position: 3
Value: 4660, MSB position: 12
Value: 2147483648, MSB position: 31

*/

 



answered Oct 1 by avibootz
...