I need to implement the following function without branching or Boolean expressions:
uint8_t func(uint32_t num, uint8_t shl)
{
if (num >= (1 << shl))
{
return shl;
}
else
{
return 0;
}
}
The first step I did was to notice that the else
part is easy:
return num / (1 << shl);
Of course, doing this in the if
part will not necessarily yield the desired result.
So I guess I need something a little more "clever" than num / (1 << shl)
.
If I could come up with an expression that would give me 1
or 0
, then I'm done.
Is there some sort of way to do this using only arithmetic/bitwise operations (i.e., no branching or Boolean expressions)?