Thread: count bit loop

  1. #1
    Registered User
    Join Date
    Oct 2010
    Posts
    33

    count bit loop

    Good morning,

    I am given the hamming distance algorithm in C which is

    Code:
    int returnDistance(int x, int y)
    {
             unsigned dist = 0;
             unsigned val = x ^ y;
    
             while(val)
             {
                    ++dist;
                    val &= val - 1;
              }
    
               return dist;
    }
    I see that this loop counts all the 1's that are found when we xor y and x, but what I'm puzzled with is how does the while loop break out? How does it know when a value is complete?

    Thanks.

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Print out the value of val in the loop and observe what happens for various input. Alternatively, just observe by using a debugger.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    Registered User
    Join Date
    Aug 2010
    Location
    Poland
    Posts
    733
    Quote Originally Posted by aromash View Post
    I see that this loop counts all the 1's that are found when we xor y and x, but what I'm puzzled with is how does the while loop break out? How does it know when a value is complete?
    Thanks.
    As I can see, the expression:
    Code:
    val &= val - 1;
    Removes one bit from val (sets one of them, which is 1, to 0). After a few iterations all bits will be set to 0. The loop breaks when val == 0 (all bits are 0).

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 1
    Last Post: 12-07-2010, 06:53 AM
  2. While loop to count the charecters of a string
    By simpatico_qa in forum C Programming
    Replies: 11
    Last Post: 04-24-2009, 03:51 AM
  3. Replies: 16
    Last Post: 11-23-2007, 01:48 PM
  4. Porting from 32 bit machine to 64 bit machine!
    By anoopks in forum C Programming
    Replies: 10
    Last Post: 02-25-2005, 08:02 PM
  5. Replies: 4
    Last Post: 11-23-2003, 07:15 AM