3

I am trying to find Hamming distance between two integers, and I got it to work with:

int count = 0;
for(int i = 0; i < 32; i++)
{
   if((x ^ y) & 1) 
       count++;
   x >>= 1;
   y >>= 1;
}

However, it does not work with:

if(x & 1 != y & 1)

When x = 1 and y = 4, the correct result is 2. However, the second version outputs 1. Sounds like I need a lesson in discrete logic.

How can I rewrite the second if-statement to make it work?

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
themennice
  • 177
  • 1
  • 9
  • 3
    If you enable all warnings, like`-Wparentheses`,you'll get a message like "warning: suggest parentheses around comparison in operand of '&' "`. You'll save time. – chux - Reinstate Monica Feb 25 '21 at 04:49

3 Answers3

9

The != operator has a higher precedence than the & operator, so the condition as written is evaluated as x & (1 != y) & 1, but you probably want (x & 1) != (y & 1) instead.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Allan Wind
  • 23,068
  • 5
  • 28
  • 38
5

If you want the Hamming distance, why not just use std::popcount?

#include <bit>
...
int count = std::popcount(x ^ y);

If you can't use C++20 then there is also a compiler intrinsic __builtin_popcount available for GCC and Clang, or __popcnt for MSVC:

#ifdef _MSC_VER
#include <intrin.h>
#define __builtin_popcount __popcnt
#endif
...
int count = __builtin_popcount(x ^ y);
Patrick Roberts
  • 49,224
  • 10
  • 102
  • 153
1

This is because bit-wise AND has less precedence than !=

https://en.cppreference.com/w/cpp/language/operator_precedence

yms
  • 10,361
  • 3
  • 38
  • 68