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

Phi*_*ldo 3 c c++

我已经掩盖了一些文档,似乎规范只需要'int'或'long'或任何能够保存"至少某些值的范围"(通常对应于由n个字节提供的最大范围).

无论如何,有没有合理的方法来要求一个正好n位/字节的整数?我甚至不需要一种指定任意长度或任何奇怪的方法,我只想要一个明确的2字节或最终4字节的类型.比如"int32"或者其他东西.

目前,我正在处理的方法是使用n长度的char数组,然后将其转换为int*并解除引用.

(我想要这样做的原因与直接从结构中读取/写入文件有关 - 我承认,有了这个,我将不得不担心结构打包和字节顺序以及其中的东西,但这是另一个问题......)

此外,与类似超级有限的嵌入式系统的"兼容性"并不是特别关注的问题.

谢谢!

use*_*011 6

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
Run Code Online (Sandbox Code Playgroud)

和相应的无符号类型

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
Run Code Online (Sandbox Code Playgroud)

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

#include <stdint.h>
uint32_t ui;
Run Code Online (Sandbox Code Playgroud)

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

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

  • 只是为了明确,不能保证`int16_t`与`short`的类型相同或者`int32_t`与`int`的类型相同,如上面的评论所暗示的那样. (2认同)
  • 更明确地说,不能保证本答案中列出的任何类型都存在给定的实现.这些类型在C11和C++ 11中都是可选的. (2认同)