Priority Encoder Lookup

Easy C Optimization Asked at Texas Instruments
Solve this problem

Given a 32-bit interrupt pending mask, return the index of the highest-priority pending source, where bit 0 is the highest priority. Return -1 when nothing is pending.

Constraints

  • Signature: `int highest_priority(uint32_t pending)`.
  • Bit 0 wins over bit 1, and so on.
  • Must not use __builtin_ctz.
  • Constant-time or logarithmic, not a 32-iteration scan.
  • Must return -1 for a zero mask.
Starter codeC
1#include <stdint.h>2 3int highest_priority(uint32_t pending) {4    // TODO: index of the lowest set bit, or -15    return -1;6}