gpt4 book ai didi

c - 这个函数的行为是什么? (二的幂)

转载 作者:太空宇宙 更新时间:2023-11-04 05:22:50 25 4
gpt4 key购买 nike

我有下一个功能:

static inline int nextPowerOfTwo(int n) {
n--;

n = n >> 1 | n;
n = n >> 2 | n;
n = n >> 4 | n;
n = n >> 8 | n;
n = n >> 16 | n;
// n = n >> 32 | n; // For 64-bit ints

return ++n;
}

但我不知道他的行为是什么(函数输出-his functionality-)

我也不知道每行的行为是什么(每行后的 n 值)。

有人能给我解释一下吗?

最佳答案

该代码来自Bit Twiddling Hacks

Round up to the next highest power of 2

unsigned int v; // compute the next highest power of 2 of 32-bit v

v--;
v |= v >> 1;
v |= v >> 2;
v |= v >> 4;
v |= v >> 8;
v |= v >> 16;
v++;

[...]

It works by copying the highest set bit to all of the lower bits, and then adding one, which results in carries that set all of the lower bits to 0 and one bit beyond the highest set bit to 1. If the original number was a power of 2, then the decrement will reduce it to one less, so that we round up to the same original value.

16、32 和 64 位的明显版本:

#include <stdint.h>

uint16_t round_u16_to_pow2(uint16_t v)
{
v--;
v |= v >> 1;
v |= v >> 2;
v |= v >> 4;
v |= v >> 8;
v++;
return v;
}

uint32_t round_u32_to_pow2(uint32_t v)
{
v--;
v |= v >> 1;
v |= v >> 2;
v |= v >> 4;
v |= v >> 8;
v |= v >> 16;
v++;
return v;
}

uint64_t round_u64_to_pow2(uint64_t v)
{
v--;
v |= v >> 1;
v |= v >> 2;
v |= v >> 4;
v |= v >> 8;
v |= v >> 16;
v |= v >> 32;
v++;
return v;
}

关于c - 这个函数的行为是什么? (二的幂),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53453693/

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