[英]How do I use an integer type of a specific size in C++?
我需要 C++ 中特定宽度的整数类型,但我不确定要使用什么类型: int
、 long
等。我意识到我可以使用sizeof
来查找每种不同整数类型的大小,但是int
、 long
和long long
是不独立于平台。 这个任务也太乏味了。
有没有办法在 C++ 中指定特定大小的整数类型(例如 32 位或 64 位整数)? 我该怎么做呢?
我认为您正在寻找的是固定宽度整数类型。 这些在标题<cstdint>
中定义。
出于您的目的,您可以坚持使用int[xx]_t
,将[xx]
替换为您需要的整数类型的宽度(以位为单位)。 uint[xx]_t
使用无符号整数类型做类似的事情。
例如,您可以使用int8_t
、 int16_t
、 uint8_t
、 uint_16t
等。
如果您需要在编译时从 constexpr 位数计算出类型,您可以执行以下操作:
#include <type_traits>
#include <iostream>
template <int NumBits, typename=void>
struct uint_selector;
template <int NumBits>
struct uint_selector<NumBits, std::enable_if_t< 0 <= NumBits && NumBits <= 8>>
{
typedef uint8_t int_type;
};
template <int NumBits>
struct uint_selector<NumBits, std::enable_if_t<8 < NumBits && NumBits <= 16 >>
{
typedef uint16_t int_type;
};
template <int NumBits>
struct uint_selector<NumBits, std::enable_if_t<16 < NumBits && NumBits <= 32 >>
{
typedef uint32_t int_type;
};
template <int NumBits>
struct uint_selector<NumBits, std::enable_if_t<32 < NumBits && NumBits <= 64 >>
{
typedef uint64_t int_type;
};
// Then use as:
int main()
{
// my_val will be the smallest standard type which is big enough type to hold 15 bits (e.g. a uint16_t)
uint_selector<15>::int_type my_val = 5;
}
如果您在编译时知道大小,则可以使用类型特征的template
特化。
#include <cstdint>
#include <type_traits>
template <std::size_t SIZE>
struct num_selector;
template<>
struct num_selector<sizeof(short)> {
using type = short;
};
template<>
struct num_selector<sizeof(int)> {
using type = int;
};
template <std::size_t SIZE>
using num_selector_t = typename num_selector<SIZE>::type;
int main() {
std::uint8_t shortish[sizeof(short)];
std::uint8_t intish[sizeof(int)];
static_assert(std::is_same_v<num_selector_t<sizeof(shortish)>, short>);
static_assert(std::is_same_v<num_selector_t<sizeof(intish)>, int>);
return 0;
}
这会假设short
和int
的大小不同,但这在大多数平台上都是合理的(如果您担心,可以通过static_assert
进行检查)。
如果您在实际读取它们之前不知道要读取多少字节(例如,字段标记的某个结尾),那么您最好选择您可能需要的最大类型并处理它.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.