From Hacker's Delight:
int hibit(unsigned int n) {
n |= (n >> 1);
n |= (n >> 2);
n |= (n >> 4);
n |= (n >> 8);
n |= (n >> 16);
return n - (n >> 1);
}
This version is for 32-bit ints, but the logic can be extended for 64-bits or higher.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…