gpt4 book ai didi

c - 计算任何数字的 log(base 2) 的最佳方法是什么?

转载 作者:太空狗 更新时间:2023-10-29 12:16:07 24 4
gpt4 key购买 nike

我需要在 Linux 内核编程中找到任意数字的 log(base 2)。此操作是否有任何内置功能?如果不是怎么计算?

最佳答案

如果整数结果对您来说足够了,您可以将多次除以 2。类似

int logFunc(unsigned int x) 
{
int log = -1;
while(x) {
log++;
x >>= 1;
}
return log;
}

如果你需要 fp 操作,你应该阅读这个:

[...]if the question was "can I just use FP in the kernel" then the answer is still a resounding NO, since other architectures may not support it AT ALL.

  Linus

Link

此外,您还可以查看:Use of floating point in the Linux kernel

编辑:如果您需要更快的版本,您可以阅读 Bit Twiddling Hacks - By Sean Eron Anderson

uint32_t v; // find the log base 2 of 32-bit v
int r; // result goes here

static const int MultiplyDeBruijnBitPosition[32] =
{
0, 9, 1, 10, 13, 21, 2, 29, 11, 14, 16, 18, 22, 25, 3, 30,
8, 12, 20, 28, 15, 17, 24, 7, 19, 27, 23, 6, 26, 5, 4, 31
};

v |= v >> 1; // first round down to one less than a power of 2
v |= v >> 2;
v |= v >> 4;
v |= v >> 8;
v |= v >> 16;

r = MultiplyDeBruijnBitPosition[(uint32_t)(v * 0x07C4ACDDU) >> 27];

关于c - 计算任何数字的 log(base 2) 的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24117790/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com