mirror of
https://github.com/ArduPilot/ardupilot.git
synced 2026-10-06 19:00:27 +08:00
Using a builtin instruction (on Cortex M3/M4/M7) saves 268 bytes.
Tested that the result is the same for all values:
```c
#include <stdio.h>
#include <limits.h>
#include <inttypes.h>
int cl2_new(unsigned int x) {
const int bitwidth = CHAR_BIT*sizeof(x);
x--;
const int clz = x ? __builtin_clz(x) : bitwidth; // clz(0) is undefined
return bitwidth-clz;
}
int cl2_old(unsigned int x) {
static const uint8_t log_2[256] = { /* log_2[i] = ceil(log2(i - 1)) */
0,1,2,2,3,3,3,3,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,
6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,
7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8
};
int l = 0;
x--;
while (x >= 256) { l += 8; x >>= 8; }
return l + log_2[x];
}
int main(int argc, char** argv) {
for (unsigned int i=1; i!=0; i++) { // 0 is not in the domain
int v_new = cl2_new(i);
int v_old = cl2_old(i);
if (v_new != v_old) {
printf("%u: %d != %d\n", i, v_new, v_old);
break;
}
}
}
```
This is Lua 5.3.6, released on 14 Sep 2020. For installation instructions, license details, and further information about Lua, see doc/readme.html.