Checking how many bits are set in an integer

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • ananddr
    New Member
    • Sep 2008
    • 2

    Checking how many bits are set in an integer

    Hi All,
    I want to check how many bits are set in an integer .
    For example,

    int a = 10;
    The binary form of 10 is 1010.
    There are two bits set to 1 in the number 10.
    Like that i have check how many bits are set to 1 in an integer.
    Can anyone help me in this....


    Thanks in advance,
    Anand.
  • newb16
    Contributor
    • Jul 2008
    • 687

    #2
    http://graphics.stanfo rd.edu/~seander/bithacks.html

    Comment

    • ananddr
      New Member
      • Sep 2008
      • 2

      #3
      I need to find it without using any loops...

      Comment

      • JosAH
        Recognized Expert MVP
        • Mar 2007
        • 11453

        #4
        Originally posted by ananddr
        I need to find it without using any loops...
        Did you read the link that was given to you? Have you read about the parallel
        counting method?

        kind regards,

        Jos

        Comment

        • curiously enough
          New Member
          • Aug 2008
          • 79

          #5
          Originally posted by ananddr
          I need to find it without using any loops...
          You mean a recursive function?

          Comment

          • donbock
            Recognized Expert Top Contributor
            • Mar 2008
            • 2427

            #6
            Originally posted by ananddr
            Hi All,
            I want to check how many bits are set in an integer .
            For example,

            int a = 10;
            The binary form of 10 is 1010.
            There are two bits set to 1 in the number 10.
            Like that i have check how many bits are set to 1 in an integer.
            Can anyone help me in this....
            Originally posted by ananddr
            I need to find it without using any loops...
            Are there any other constraints imposed on this homework problem?

            Another approach is divide-and-conquer: recognize that you can break your input value into smaller chunks (bytes, nibbles, or even bits) and that the sum of the number of bits set in all the chunks is the same as the number of bits set in the input value. For a small enough chunk it becomes efficient to use a lookup table. However, you can't break the input value into chunks unless you know how many chunks fit in the input type. Take a look at <limits.h> to see if you can think of a reasonably portable way to do this.

            Cheers,
            donbock

            Comment

            Working...