0

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?

user3692521
  • 2,563
  • 5
  • 27
  • 33
  • Unless I'm crazy, just `return m & (m-1);` will work. (Though the underflow might technically be UB.) – David Schwartz Mar 18 '15 at 04:57
  • You'd need `unsigned char` IIRC. And that UB is more than "technically UB", modern optimizers will use it to prove m!=0. That proof can have rather unexpected effects on your code. – MSalters Mar 18 '15 at 08:22

2 Answers2

0

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

David Schwartz
  • 179,497
  • 17
  • 214
  • 278
0

It's wrong. The mistaken idea is that char is 8 bit.

It's also pointless. The presumed problem is that m can have more bits than char (true) so that "unnecessary" bits are masked off.

But m is sign-extended. That means the sign bit is copied to the higher bits. Now, when we're comparing x==0 we're checking whether all bits are zero, and with x & 0xff we're comparing if the lower 8 bits are zero. If the 8th bit of x is copied to all higher positions (by sign extension), then the two conditions are the same regardless of whether the copied bit was 0 or 1.

MSalters
  • 173,980
  • 10
  • 155
  • 350