是否有可能在C/ c++中获得确定/绝对大小的类型?

is it possible to get definitive/absolute sized types in C/C++?

本文关键字:类型 有可能 c++ 是否      更新时间:2023-10-16

我已经忽略了一些文档,似乎规范只要求'int'或'long'或其他能够容纳"至少一定范围的值"(通常对应于n个字节提供的最大范围)。

无论如何,是否有一个合理的方法来要求一个恰好n位/字节的整数?我甚至不需要指定任意长度或任何奇怪的东西,我只想要一个确定为2字节的类型,或者确定为4字节的类型。比如"int32"之类的。

目前,我处理这个问题的方式是有一个长度为n的字符数组,然后将其转换为int *并解引用。

(我想要这个的理由与直接从结构体读取/写入文件有关-我承认,有了这个,我将不得不担心结构体包装和端序和东西,但这是另一个问题…)

同样,与类似的超级有限的嵌入式系统的"兼容性"也不是一个特别关注的问题。

谢谢!

c++11标准定义了确定大小的整数类型,只要它们在目标体系结构上可用。

#include <cstdint>
std::int8_t  c; //  8-bit unsigned integer
std::int16_t s; // 16-bit unsigned integer
std::int32_t i; // 32-bit unsigned integer
std::int64_t l; // 64-bit unsigned integer

和对应的unsigned类型

std::uint8_t  uc; //  8-bit unsigned integer
std::uint16_t us; // 16-bit unsigned integer
std::uint32_t ui; // 32-bit unsigned integer
std::uint64_t ul; // 64-bit unsigned integer

如注释所述,这些类型在C中也可以从stdint.h头文件中获得,而不需要std::命名空间前缀:

#include <stdint.h>
uint32_t ui;

除了确定大小的类型外,这些头文件还定义了类型

  • 至少n位宽,但可能更大,例如int_least16_t至少16位
  • 提供至少n位但可能更大的整数的最快实现,例如至少32位的std::int_fast32_t

<cstdint>中声明的类型,比如int32_t,要么就是那个位数[在这个例子中是32],要么在体系结构不支持这个大小的值时不存在。还有int_fast32_t类型,它保证保存32位值,但可能更大,int_fast32_t类型也有类似的保证。

当前的c++标准提供了固定宽度的整数类型,如std::int16_t std::uint16_t,其中16表示以位为单位的类型大小。

您可以使用<stdint.h>中的类型,但是您不能确定是否有您想要的类型。

如果你的架构确实有确切的32位类型,这是很有可能的,那么你可以使用int16_t, uint16_t, int32_tuint32_t,如果不是,int_fast32_tuint_fast32_t以及int_least32_tuint_least32_t等类型总是可用的。

相关文章: