Saturday, February 5, 2011

Caculate how many one in a bit format of int value

Everyone knows that in computer, no matter what type you are using, finally it will be represent with bits , 0 and 1 .   For example
INT value    Bit
1                  0001
2                  0010
3                  0011
4                  0100
and so on....

A couple days ago, I was asked, given an int value, can you print out it in bit format, and caculate how many 1 in the bit level.

First of all, it is quite easy to get the bit string of the int value, just use convert function.
Secondly , caculate how many one in the bit string, you can use & operator and >> operator


   1:  class MainClass
   2:      {
   3:          static readonly int LENOFBIT = 8;
   4:          public static void Main (string[] args)
   5:          {
   6:              int iValueToTest = 12345;
   7:              string strBit = Convert.ToString(iValueToTest,2);
   8:              Console.WriteLine("int value {0} in bit format is {1}",iValueToTest,strBit);
   9:              Console.WriteLine("there are {0} one in bit format",CaculateOne(iValueToTest));
  10:                          
  11:          }
  12:          
  13:          static int CaculateOne(int iValue)
  14:          {
  15:              int iResult = 0;
  16:              int iLen = sizeof(int);
  17:              for(int i=0;i<iLen * LENOFBIT;i++)
  18:              {
  19:                  if((iValue & 1) == 1)
  20:                  {
  21:                      iResult ++;
  22:                  }
  23:                  iValue = iValue >> 1;
  24:              }
  25:              return iResult;
  26:          }
  27:          
  28:      }

You may ask , what the hell this is used for? assume you are implementing a user permission system,  you can use each bit to represent a permission, thus an int value can represent 32 permissions.

No comments:

Post a Comment