是否有可能在C/ c++中获得确定/绝对大小的类型?
is it possible to get definitive/absolute sized types in C/C++?
我已经忽略了一些文档,似乎规范只要求'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_t
和uint32_t
,如果不是,int_fast32_t
和uint_fast32_t
以及int_least32_t
和uint_least32_t
等类型总是可用的。
- 是否有可能具有放入容器的移动操作的类型?
- 是否有可能获得未知类的班级成员的计数和类型
- 在C 中,是否有可能在不兼容类型的std ::向量对象之间传输不同类型的缓冲区
- 即使数据类型不同,是否有可能将帧的参数作为参数传递给回溯中的另一个帧
- 是否有类型特征显示一种类型是否可能包含其他类型的值
- 编译器是否有可能检测整数溢出或其他数据类型溢出的可能性
- 有可能在c++中创建一个占用不到一个字节内存的类型吗
- 是否有可能在c++中为向量(或其他类似的数据类型)编写用户迭代类
- 在c++中,是否有可能获取函数的返回类型,以便在不调用该函数的情况下声明该变量?
- 是否有可能忽略c++11的尾随返回类型特性,而使用c++14的函数返回类型扣除特性?
- 在c++中基类销毁期间是否有可能知道派生实例类型?
- 是否有可能在没有编译失败的情况下推断类型是否不完整
- 是否有可能重载一个函数以接受具有非类型模板参数的所有实例?
- 是否有可能在不传递参数的情况下获得函数的返回类型?
- 在c++中,当元组的元素索引在运行时已知时,是否有可能获得该元素的类型?
- 是否有可能创建一个向量映射,其中向量可以是任何类型
- 是否有可能在c++中为嵌入式平台创建一个新的原语类型?
- 是否有可能描述某个原始类型的子类型
- 在visual basic、java或c++中是否有可能拥有无限精度的浮点数据类型?
- 是否有可能通过重复的std::元组的类型名来获取