Mailing Lists: Apple Mailing Lists

Image of Mac OS face in stamp
 
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Count bits



For scalar code you can also do the following:

inline int countBits (int i)
{
	i = (i & 0x55555555) + ((i >> 1) & 0x55555555);
	i = (i & 0x33333333) + ((i >> 2) & 0x33333333);
	i = (i & 0x0F0F0F0F) + ((i >> 4) & 0x0F0F0F0F);
	i = (i & 0x00FF00FF) + ((i >> 8) & 0x00FF00FF);
	return (i & 0x0000FFFF) + ((i >> 16) & 0x0000FFFF);
}

This can easily be modified and extended to work with 64 bits with only one extra line of calculation

Martin


On 28 Nov 2005, at 16:02, Cameron Hayne wrote:

On 28-Nov-05, at 5:51 AM, Bruno Causse wrote:
I seek the fastest method to count the bits has 1 in a unsigned long long

I use the following code for 32-bit unsigned int values - it is easily modified for other value sizes. It makes use of a pre- computed array 'BitsInChar' (which is independent of the data and calculated at program initialization):


// This is derived from the 'precomputed_bitcount' routine
// on the web page "Counting Number of On Bits in an Integer"
// by Gurmeet Singh Manku
// http://www-db.stanford.edu/~manku/bitcount/ bitcount.html


            count = BitsInChar[(value      ) & 0xFFu]
                      +  BitsInChar[(value >>  8) & 0xFFu]
                      +  BitsInChar[(value >> 16) & 0xFFu]
                      +  BitsInChar[(value >> 24) & 0xFFu];

--
Cameron Hayne
email@hidden


_______________________________________________ Do not post admin requests to the list. They will be ignored. PerfOptimization-dev mailing list (email@hidden) Help/Unsubscribe/Update your Subscription: http://lists.apple.com/mailman/options/perfoptimization-dev/email@hidden

This email sent to email@hidden
References: 
 >Count bits (From: Bruno Causse <email@hidden>)
 >Re: Count bits (From: Cameron Hayne <email@hidden>)



Visit the Apple Store online or at retail locations.
1-800-MY-APPLE

Contact Apple | Terms of Use | Privacy Policy

Copyright © 2007 Apple Inc. All rights reserved.