Bit Count

InertiaM

Well-known member
Joined
Nov 3, 2007
Messages
663
Location
Kent, UK
Programming Experience
10+
Is there a simple way to count the number of bits used to make up an integer value? For example

VB.NET:
  dim iValue as integer = 1746 ' => 11011010001
  dim iBitCount as integer = BitCount (iValue) ' should be 6

I know I can do it with a FOR..NEXT loop and check the individual bits, but I just wondered if there was a function that I dont know about.
 
Think John misunderstood the question.

You want to know, for the binary representation, how many ONEs there are in it?

Here's a bit of a cheat/lame way but it's a good one liner:

System.Convert.ToString(1746, 2).Replace("0", "").Length


Covert 1746 to binary string, repalce all the 0 with nothing, and the lenght of the result is the number of 1s in the string
 
It may be a cheat way, but it'll do for me thanks :D
 
Back
Top