Since @lritter mentioned a favourite #bithack yesterday, I'm inspired to mention mine.

I once had to calculate the mean, rounded down, of two 32-bit integers, in _original_ Thumb assembler, avoiding integer overflow. In _Arm_ asm it's easy: ADDS + RRX, shifting the 33rd bit of the sum back out of the carry flag. But trad Thumb has no RRX.

I found a Thumb version of GNU superopt and asked it how.

It said: _start by XORing the two numbers_. You know you're into fun territory when that happens!

Here's an informal and (hopefully simple to understand) by-example derivation of "next larger integer with same popcount" implementation that saturates to known when none exists. From there builds "closest smaller integer", "at runtime selected direction" and shows the connection to recent post by @harold that walks to "closest". If I didn't screw up it should be UB free.

https://marc-b-reynolds.github.io/math/2023/11/09/PopNextPrev.html

#bithack #popcount

Popcount walks: next, previous, toward and nearest

Informal (and by-example) derivation of walking adjacent integers with the same population count as the input.

Marc-B-Reynolds.github.io

My insufferable brain keeps repeating to me (for the past week) that if 'x' has popcount 'p' then bit_gather(~0,x) is the integer with the lowest 'p' bits set.

Maybe this post will make it stop.

(edit: PEXT on intel)

#bithack #popcount