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

1 Answer

0 votes
/**
 * Demonstrates how to find the position of the most significant set bit (MSB)
 * in an unsigned 32-bit integer.
 */
object MostSignificantBitDemo {

    /**
     * Returns the zero-based position of the most significant set bit (MSB)
     * in an unsigned 32-bit integer.
     *
     * Examples:
     *   1u  -> 0
     *   2u  -> 1
     *   8u  -> 3
     *   15u -> 3
     *
     * @param value Unsigned integer to examine.
     * @return The MSB position, or null if the value is 0.
     */
    fun msbPosition(value: UInt): Int? {
        if (value == 0u) {
            return null
        }

        return UInt.SIZE_BITS - 1 - value.countLeadingZeroBits()
    }

    @JvmStatic
    fun main(args: Array<String>) {
        val testValues: List<UInt> = listOf(
            0u,
            1u,
            2u,
            8u,
            15u,
            0x1234u,
            0x80000000u
        )

        for (value in testValues) {
            val position: Int? = msbPosition(value)

            if (position != null) {
                println("Value: $value, MSB position: $position")
            } else {
                println("Value: $value, no bits are set")
            }
        }
    }
}



/*
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
...