Returns how many bits are necessary to hold a certain number : Binary Bit « Data Types « C# / C Sharp






Returns how many bits are necessary to hold a certain number

        
/* Copyright (c) 2010 Michael Lidgren

Permission is hereby granted, free of charge, to any person obtaining a copy of this software
and associated documentation files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom
the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or
substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
USE OR OTHER DEALINGS IN THE SOFTWARE.

*/
using System;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Text;
using System.Text.RegularExpressions;

namespace Lidgren.Network
{
  /// <summary>
  /// Utility methods
  /// </summary>
  public static class NetUtility
  {


    /// <summary>
    /// Returns how many bits are necessary to hold a certain number
    /// </summary>
    [CLSCompliant(false)]
    public static int BitsToHoldUInt(uint value)
    {
      int bits = 1;
      while ((value >>= 1) != 0)
        bits++;
      return bits;
    }

    /// <summary>
    /// Returns how many bytes are required to hold a certain number of bits
    /// </summary>
    public static int BytesToHoldBits(int numBits)
    {
      return (numBits + 7) / 8;
    }
  }
}

   
    
    
    
    
    
    
    
  








Related examples in the same category

1.Using the Bitwise Complement Operators with Various Data TypesUsing the Bitwise Complement Operators with Various Data Types
2.Obtaining the Most Significant or Least Significant Bits of a NumberObtaining the Most Significant or Least Significant Bits of a Number
3.Binary Data TestBinary Data Test
4.Binary Network Byte OrderBinary Network Byte Order
5.Int binary
6.Get hash code for a byte array
7.Clone a byte array
8.Count the number of bit
9.Bit Helper
10.Bit shifting for int and long value