有可能知道整数类型中有多少位吗

Is it possible to know how many bits in integer type?

本文关键字:多少 类型 整数 有可能      更新时间:2023-10-16

我想使用一些整数类型作为位掩码。我想知道对于哪个n,保证从0到2^n-1的任何数字在这种类型中都是可用的。(实际上我要用uintmax_t

我知道它通常是8 * sizeof(uintmax_t)(或者可能是CHAR_BIT * sizeof(uintmax_t)),但我想它不能保证。

所以我想,用另一种方式找到这个n

我该如何做到这一点?

sizeof运算符与CHAR_BIT 结合使用没有错

const std::size_t nBits = CHAR_BIT * sizeof(some_integer_type);

这也适用于其他构建的int类型以及用户定义的类型。

使用cstdint include。

它为整数类型提供了跨平台固定大小的typedefs,并为其限制提供了宏常量。

#include <cstdint>
std::int8_t Signed = 0;    // granted to 8bit size.
std::uint8_t Unsigned = 0; // granted to 8bit size.
Signed = INT8_MAX;        // store the max value for a signed 8bit value.
Unsigned = UINT8_MAX;      // store the max value for an unsigned 8bit value.

希望能有所帮助。

答案是1+log2((UINTMAX_MAX>>1)+1)

它也可以通过对具有重复移位的比特进行计数来导出。