Skip to content

Instantly share code, notes, and snippets.

@astoeckel
Last active January 13, 2024 00:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save astoeckel/457911d033a6637b97e2b58ebca1e643 to your computer and use it in GitHub Desktop.
Save astoeckel/457911d033a6637b97e2b58ebca1e643 to your computer and use it in GitHub Desktop.
Integer log2 with 14-bit fractional part in C/C++
#include <stdint.h>
int32_t log2_f14(int32_t x) {
// We don't support zero or negative values, just return zero in that case
if (x <= 0) {
return 0;
}
// Compute the integer logarithm
int32_t log2_int = 0;
int32_t x_tmp = x;
while (x_tmp > 1) {
log2_int += 1;
x_tmp >>= 1;
}
// Compute the fractional part; return if there is no fractional part
x -= (int32_t(1) << log2_int);
if (x <= 0) {
return log2_int << 14;
}
// Scale the fractional part to a constant 14-bit dynamic range
x <<= (31 - log2_int);
x >>= 17;
// Evaluate a polynomial of order 3 approximating the shape of the log
// function on the fractional part
int32_t res = 0;
res = ((res * x) >> 14) + 2529;
res = ((res * x) >> 14) - 9324;
res = ((res * x) >> 14) + 23174;
res = ((res * x) >> 14);
return res + (log2_int << 14);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment