Atlanta Custom Software Development 

 
   Search        Code/Page
 

User Login
Email

Password

 

Forgot the Password?
Services
» Web Development
» Maintenance
» Data Integration/BI
» Information Management
Programming
  Database
Automation
OS/Networking
Graphics
Links
Tools
» Regular Expr Tester
» Free Tools

Counting Bits
[ All Languages » VB »  Math]

Total Hit ( 3308)

Rate this article:     Poor     Excellent 

 Submit Your Question/Comment about this article

Rating


 


It seems that the only way to count the number of 1's or 0's in a binary value is creating a loop that iterates on all the 16 or 32 bits of the number. There is, however, a faster algorithm:

Click here to copy the following block
Function BitCount (ByVal number As Long) As Integer
 Dim bits As Integer, temp As Long
 temp = number
 Do While temp
  temp = temp And (temp - 1)
  bits = bits + 1
 Loop
 BitCount = bits
End Function

While this code apparently makes little sense, it can be explained knowing that the expression n And (n - 1) actually drops the least significant (i.e. the rightmost) bit that is set in n. If you repeat this operation until the number becomes zero, you can indirectly evaluate how many 1's were in the number. On the average this requires half of the iterations needed by the standard method.


Submitted By : Nayan Patel  (Member Since : 5/26/2004 12:23:06 PM)

Job Description : He is the moderator of this site and currently working as an independent consultant. He works with VB.net/ASP.net, SQL Server and other MS technologies. He is MCSD.net, MCDBA and MCSE. In his free time he likes to watch funny movies and doing oil painting.
View all (893) submissions by this author  (Birth Date : 7/14/1981 )


Home   |  Comment   |  Contact Us   |  Privacy Policy   |  Terms & Conditions   |  BlogsZappySys

© 2008 BinaryWorld LLC. All rights reserved.