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

1 Answer

0 votes
using System;

namespace MsbDemo
{
    internal static class Program
    {
        /// <summary>
        /// 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
        ///
        /// Returns:
        ///   -1 if the value is 0.
        /// </summary>
        /// <param name="value">
        /// Unsigned integer to examine.
        /// </param>
        /// <returns>
        /// Zero-based index of the highest set bit, or -1 if no bits are set.
        /// </returns>
        private static int GetMsbPosition(uint value)
        {
            if (value == 0) {
                return -1;
            }

            int position = 0;

            while (value > 1) {
                value >>= 1;
                position++;
            }

            return position;
        }

        private static void Main()
        {
            uint[] testValues =
            {
                0u,
                1u,
                2u,
                8u,
                15u,
                0x1234u,
                0x80000000u
            };

            foreach (uint value in testValues)
            {
                int msbPosition = GetMsbPosition(value);

                if (msbPosition >= 0) {
                    Console.WriteLine(
                        "Value: {0}, MSB position: {1}",
                        value,
                        msbPosition);
                }
                else {
                    Console.WriteLine(
                        "Value: {0}, no bits are set",
                        value);
                }
            }
        }
    }
}



/*
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 Sep 30 by avibootz
...