1

In C++20, to remove trailing zeros in the binary representation of an integer you can use a >>= std::countr_zero(a);. I think it is optimized by the compiler so very fast.

What would be the C equivalent, is there a faster way to do it than a while loop?

while ((a & 1) == 0) { a >> 1; }
Lundin
  • 195,001
  • 40
  • 254
  • 396
  • probably `a >>= whatever_the_countr_zero_function_is_called_in_c(a);` – user253751 Jul 11 '22 at 09:00
  • 5
    I added the C++ tag since this would be one of the few cases where it is correct to use both tags at once (when comparing the languages). – Lundin Jul 11 '22 at 09:00
  • 1
    You might like [bit twiddling hacks](https://graphics.stanford.edu/~seander/bithacks.html#ZerosOnRightLinear) – pmg Jul 11 '22 at 09:03
  • It's not obvious which method that's the fastest, it depends a lot on the ISA. I showed the countr_zero, the while loop and the bit twiddling hack into Godbolt for x86 but got very different asm for all 3 cases. Curiously, the `std::countr_zero(a)` boiled down to a `rep` call in the optimized code on gcc x86. – Lundin Jul 11 '22 at 09:11
  • `countr_zero` is simply a standardised version of the various intrinsics or compiler built-ins that are already available. Which compiler/CPU are you using? – Alan Birtles Jul 11 '22 at 09:17
  • 1
    What's wrong with the `while` loop? It's clear enough that optimizers should be able to recognize it. – MSalters Jul 11 '22 at 09:24

0 Answers0