I have the following function:
uint16_t foo(uint8_t input)
{
uint16_t N = 38;
if (!(input&1))
{
N = 0;
}
else
{
if ((input&2) >> 1)
{
N = ~N;
}
}
return N;
}
And I would like to have it rewritten without ifs
, just as an inline function which transforms 38
into either 0,38
or 65497
given input
and using only standard C bit-twiddling operations.
The point is not that compiler could inline the function, or the function to be fast, but just to get rid of the branches and be constant-time regardless what the input
is.
The first if
is easy:
uint16_t c = ((input&1)^1)-1;
N &= c;
but I'm having troubles finding some simple way to do that conditional negation.
7 operations and no multiplies, builds on njuffa's comment:
Demo