Problems in bitwise operation

Dear Sirs,
I need to write a function that, given in input two long numbers in the interval (0,pow(2,L))(L is given in input), can count how many different bits they have. For example, given 9 (01001) and 0(00000), it should give me distance=2. The function is the following:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
int hammingDist(long genome1, long genome2, int L){
 if(genome1==genome2){
  return 0;
 } else {
  long bit = (long)1;
  int distance = 0;
  for(int i=0; i<L;i++){
   long mask1 = genome1 && (bit<<i);
   long mask2 = genome2 && (bit<<i);
   if (mask1!=mask2){
    distance++;
   }
  }
 }
 return distance;
}


I think that the algorithm is correct, but something in the code not. I call the function with the following lines:

1
2
3
4
for(int j=0; j<dimension; j++){
 hammingdistance = hammingDist((long)line, (long)j, L);
 cout <<j <<" " <<hammingdistance <<endl;
}


where line is an integer defined some lines before.
Indeed the program output is the following (note that the first row is line):


9
0 5
1 0
2 0
3 0
4 0
5 0
6 0
7 0
8 0
9 0
10 0
11 0
12 0
13 0
14 0
15 0
16 0
(...)


Note that for all the values of line I choose (0-32) the output is exactly the same.
Could you please help me to solve the problem? Because I don't really know how I can do.

Thank you very much,

Andrea

Last edited on
If this compiles, than you probably have a global variable called distance and you're returning that from your function, as the variable called distance in your function is not visible to the return statement. Move your return statement right after your for loop. Also && is the logical and operator, you need the & a.k.a. bitwise and operator.
The problem is on line 8/9 in your hammingDist() function.

&& is the logical operator (leads to true/false)
& is bitwise operator to mask the bit
Thank you very much! That was the problem and I don't think I would note it.

Andrea
Topic archived. No new replies allowed.