If you are on a recent-ish x86 or x86-64 platform (and you probably are), use the bsr
instruction which will return the position of the highest set bit in an unsigned integer. It turns out that this is exactly the same as log2(). Here is a short C or C++ function that invokes bsr
using inline ASM:
#include <stdint.h>
static inline uint32_t log2(const uint32_t x) {
uint32_t y;
asm ( "bsr %1, %0
"
: "=r"(y)
: "r" (x)
);
return y;
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…