Hacker News new | past | comments | ask | show | jobs | submit login

While it seems to be true gcc and clang don't recognize this pattern even when implemented correctly, your program becomes an infinite loop if the highest bit is set (negative), because 'i' will never become 0.

Example with int8_t:

  int8_t i = -127; // 0b10000001
  i >>= 1; // 0b11000000
  i >>= 1; // 0b11100000
  i >>= 1; // 0b11110000
  i >>= 1; // 0b11111000
  i >>= 1; // 0b11111100
  i >>= 1; // 0b11111110
  i >>= 1; // 0b11111111
  i >>= 1; // 0b11111111 ad infinitum
One needs to be careful when using >> (shift right) with signed integers.

So your program is not equivalent to popcount.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: