【发布时间】:2022-01-06 03:57:24
【问题描述】:
我想以二进制格式获取等于 1 的索引,现在我使用这样的代码:
inline static uint8_t the_index(uint32_t val){
return uint8_t(log(val & ((~val) + 1))/log(2));
}
我想知道是否有其他方法可以实现相同的目标?有没有可能使用位操作来解决这个问题?
我这样做是为了迭代一个值并构建一些取决于迭代位置的操作,伪代码如下:
while (temp) {
auto cur_index = the_index(temp);
auto window = ((1 << i) - 1) << cur_index;
if (((temp & window) ^ window) == 0) {
//....do something
}
temp &= temp - 1;
}
【问题讨论】:
-
该值可以设置多个位吗?在那种情况下,你想发生什么?
-
听起来像
std::countr_zero? -
@HolyBlackCat:
log代码建议找到最高有效位集。那是std::bit_width。 -
@MSalters
val & ((~val) + 1)将除最低有效位1之外的所有位清零。 -
直到 C++20,
countr_zero在 Boost.Core 中可用;现场演示:godbolt.org/z/hvdx9x6PE.
标签: c++ algorithm bit-manipulation bitwise-operators