If the range of input values ββis quite limited, for example 0..255, you can use the search table:
const unsigned char roundup_pow2 [] = {1, 2, 2, 2, 4, 4, 4, 4,
};
unsigned int restricted_roundup_power2 (int v)
{
if (v >= 0 && v <= sizeof roundup_pows)
return roundup_pow2 [v];
return 0;
}
The range can be expanded with reuse:
unsigned int roundup_power2 (int v)
{
if (v >= 0 && v <= sizeof roundup_pows)
return roundup_pow2 [v];
return 8 + roundup_power2 (v >> 8);
}
Of course, a simple program (on the left as an exercise) can be written to create tabular values, and not to calculate them manually.
source
share