2 ms·
I am of the opinion that tasks like finding the least significant set bit should be inside the standard library of all languages, so that compilers (including J
by kccqzy 3y ago
I am of the opinion that tasks like finding the least significant set bit should be inside the standard library of all languages, so that compilers (including JIT ones) can use the efficient CPU instruction to calculate it, like bsr/bsf on x86 ones. This is the first time I've heard of the `word & -word` trick because in C/C++ I'd just use __builtin_ctzll and __builtin_clzll.
Oh and same for saturating arithmetic.
- pizlonator 3y agoTotally. The hamming weight thing this post does is available as an instruction on most cpus.
- emmelaich 3y agoExposed as popcount() in recent versions of Python and C++.
- corysama 3y agoSame. I’m very happy about the addition of https://en.cppreference.com/w/cpp/numeric/countr_zero https://en.cppreference.com/w/cpp/numeric/countr_zero There’s a proposal to get them to work with std::bitset. https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2024/p3103r0.html https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2024/p31... Don’t know if it got anywhere. Meanwhile, you might appreciate the venerable https://graphics.stanford.edu/~seander/bithacks.html https://graphics.stanford.edu/~seander/bithacks.html
- anonymoushn 3y agoYou end up using some of these tricks even if you can access ctz, because it's faster to mask off the lowest bit in a way that doesn't depend on the output of the ctz instruction.
- deleted 3y ago[deleted]
- jandrewrogers 3y agoAt least on x86 processors, most idiomatic bit manipulation expressions like `word & -word` or `word & (word - 1)` compile to a single fast ALU instruction. __builtin_clz and similar are comparatively more expensive on many architectures.
- ndesaulniers 3y agoGCC now implements __builtin_ctzg for things like C23 _BitInt (and more). Makes implementing C23 stdbit.h more straightforward.