How to represent (x ^ y) & 1 in another form?

Viewed 109

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?

3 Answers

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.

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);
Related