</>EmbeddedInterview

Count leading zeros of a 32-bit number.

Easy"Coding: Systems, Bitmaps & Virtualization"
#include <stdint.h>

unsigned clz32(uint32_t x)
{
    if (x == 0) return 32;
    unsigned n = 0;
    if (!(x & 0xFFFF0000u)) { n += 16; x <<= 16; }    /* binary search on the top bits */
    if (!(x & 0xFF000000u)) { n += 8;  x <<= 8;  }
    if (!(x & 0xF0000000u)) { n += 4;  x <<= 4;  }
    if (!(x & 0xC0000000u)) { n += 2;  x <<= 2;  }
    if (!(x & 0x80000000u)) { n += 1; }
    return n;
}
/* clz32(1) = 31, clz32(0x00F00000) = 8 */

Points: five steps instead of 32; in production use __builtin_clz(x) (undefined for 0) which is one CLZ instruction on Armv5+ / Cortex-M3+. Uses: 31 - clz = index of the highest set bit (floor log2), normalising fixed-point values, finding the highest-priority ready task in a bitmap scheduler.