在 C++ 中,找出存储给定 int 需要多少位的最快方法是什么?
我可以多次尝试将数字除以 2,但除法速度很慢。有什么快速的方法吗?
编辑:
非常感谢大家的回答。当我在帖子中说 int
时,我指的是任何 4 字节的 int。例如,如果我存储 30665,我想得到 15 位的结果。
最佳答案
在 C++20 中你只需要使用 std::bit_width()
或其等效物
return std::numeric_limits<decltype(x)>::digits - std::countl_zero(x);
如果您使用的是较旧的 C++ 标准,请使用 boost::multiprecision::msb()
它会自动映射到当前编译器的适当内在函数,如 __builtin_clz()
或 _BitScanReverse()
... 或者使用 #ifdef
并根据当前编译器手动切换实现
return boost::multiprecision::msb(x); // Cross-platform
int index;
return _BitScanReverse(&index, n)) ? index + 1 : 1; // MSVC, ICC
return 32 - _lzcnt_u32(n); // ICC
return 32 - __builtin_clz(X)); // GCC, Clang
关于c++ - 表示给定 `int` 的最小位数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21191307/