Calculate how many bits is enough to hold ivalue. - CSharp Language Basics

CSharp examples for Language Basics:Number

Description

Calculate how many bits is enough to hold ivalue.

Demo Code


using Microsoft.Win32;
using System.Text;
using System.IO;/*from w  w w. java  2s . c o  m*/
using System;

public class Main{
        /// <summary>
        /// Calculate how many bits is enough to hold ivalue.
        /// </summary>
        /// <param name="ivalue">source value.</param>
        /// <returns>bits number.</returns>
        public static int BitPrecision(ulong ivalue)
        {
           if (ivalue == 0) return 0;
            int l = 0, h = 8 * 4; // 4: sizeof(ulong)
           while (h-l > 1)
           {
              int t = (int) (l+h)/2;
              if ((ivalue >> t) != 0)
                 l = t;
              else
                 h = t;
           }
           return h;
        }
}

Related Tutorials