Find the highest order bit in C [duplicate]

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.

Leave a Comment