有可能知道整数类型中有多少位吗
Is it possible to know how many bits in integer type?
我想使用一些整数类型作为位掩码。我想知道对于哪个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。
它为整数类型提供了跨平台固定大小的typedef
s,并为其限制提供了宏常量。
#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)
它也可以通过对具有重复移位的比特进行计数来导出。
相关文章:
- ArduinoJson 6.15.2:JsonObject没有命名类型
- C++有多少类型的循环
- 在 c++ 中,能够将浮点类型加 1 的最大整数是多少?
- 定义类型的成本/开销是多少?
- 在 C/C++ 中,混合类型整数数学所需的最小类型向上转换是多少?
- 在使用分段寻址模式的 16 位系统上,"size_t"、"uintptr_t"、"intptr_t"和"ptrdiff_t"类型的实际大小是多少?
- 对于多少种类型的 x86 处理器,Ngen 和 .net 本机一次创建本机代码
- 使用auto时派生的类型的优先级是多少
- 转换为 int 或其他类型的某些内存地址的十六进制值的大小是多少?
- 增强变体支持的数据类型有多少?
- 在c++中,枚举数据类型消耗多少内存
- c++中枚举类型data的大小是多少?
- 类型ID的成本是多少?
- std::variant可以定义多少类型
- 如果在保持相同类型的同时添加constness, static_cast运行时开销是多少?
- 有可能知道整数类型中有多少位吗
- 在C++中使用Templates时,编译器如何知道要实例化多少数据类型
- 在32位Linux中,有符号的长-长数据类型的最大大小是多少
- 接收一串"chars",并尝试使用指针计算其中有多少个相同类型
- 常见数据类型的长度是多少