Search code examples
c++gray-code

How to tell if two 8-bit chars are gray codes in c++?


The problem is to tell if two 8-bit chars are gray codes(differ only in 1 bit) in C++? I found an elegant C++ solution:

bool isGray(char a, char b) {
    int m = a ^ b;
    return m != 0 && (m & (m - 1) & 0xff) == 0;
}

I was confused that what does the "& 0xff" do?


Solution

  • & 0xff extracts the 8 lowest bits from the resulting value, ignoring any higher ones.