Thread: Number of set bits

Hybrid View

Previous Post Previous Post   Next Post Next Post
  1. #1
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,005
    Steve's 'Cute Code' collection shows a loopless trick to "Count the number of '1' bits in a 32 bit word":
    Code:
       n = (n & 0x55555555) + ((n & 0xaaaaaaaa) >> 1);
       n = (n & 0x33333333) + ((n & 0xcccccccc) >> 2);
       n = (n & 0x0f0f0f0f) + ((n & 0xf0f0f0f0) >> 4);
       n = (n & 0x00ff00ff) + ((n & 0xff00ff00) >> 8);
       n = (n & 0x0000ffff) + ((n & 0xffff0000) >> 16);
    [edit]This has come up here a couple times, too.
    Last edited by Dave_Sinkula; 09-20-2004 at 12:44 PM.
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

  2. #2
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Quote Originally Posted by Dave_Sinkula
    Steve's 'Cute Code' collection shows a loopless trick to "Count the number of '1' bits in a 32 bit word":
    Code:
       n = (n & 0x55555555) + ((n & 0xaaaaaaaa) >> 1);
       n = (n & 0x33333333) + ((n & 0xcccccccc) >> 2);
       n = (n & 0x0f0f0f0f) + ((n & 0xf0f0f0f0) >> 4);
       n = (n & 0x00ff00ff) + ((n & 0xff00ff00) >> 8);
       n = (n & 0x0000ffff) + ((n & 0xffff0000) >> 16);
    [edit]This has come up here a couple times, too.
    You could use a lookup table if you want it faster.

    Quzah.
    Hope is the first step on the road to disappointment.

  3. #3
    Registered User
    Join Date
    Feb 2003
    Posts
    175
    Code:
      n = (n & 0x55555555) + ((n & 0xaaaaaaaa) >> 1);
       n = (n & 0x33333333) + ((n & 0xcccccccc) >> 2);
       n = (n & 0x0f0f0f0f) + ((n & 0xf0f0f0f0) >> 4);
       n = (n & 0x00ff00ff) + ((n & 0xff00ff00) >> 8);
       n = (n & 0x0000ffff) + ((n & 0xffff0000) >> 16);

    Can anybody explain, how does this work?

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Help counting number of bits set in an integer
    By JayDiddums10 in forum C Programming
    Replies: 5
    Last Post: 12-07-2006, 03:21 PM
  2. Logical errors with seach function
    By Taka in forum C Programming
    Replies: 4
    Last Post: 09-18-2006, 05:20 AM
  3. The new FAQ
    By Hammer in forum A Brief History of Cprogramming.com
    Replies: 34
    Last Post: 08-30-2006, 10:05 AM
  4. C help for network animator
    By fastshadow in forum Tech Board
    Replies: 7
    Last Post: 03-17-2006, 03:44 AM
  5. problem with open gl engine.
    By gell10 in forum Game Programming
    Replies: 1
    Last Post: 08-21-2003, 04:10 AM