stint .h中的c++标准类型大小

C++ standard type sizes in stdint.h

本文关键字:类型 标准 c++ 中的 stint      更新时间:2023-10-16

我使用std::uint32_t,出于某种原因,它是一种不同的数据类型,而不是unsigned long,这是我的平台上的unsigned 32 (ARM Cortex M4 K20)…什么好主意吗?

没关系,我猜有时候你想要可变大小的类型:

typedef unsigned short Integer16;
typedef std::uint32_t Integer32;
typedef unsigned int FastInteger16;
typedef unsigned long FastInteger32;

有什么问题吗?

类型std::uint32_t应该是32位的无符号整数。

但这意味着它可以是unsigned intunsigned long
这两个值可能都是32位长(取决于实现)。

或者禁止任何方式做定义告诉我如果std::uint32_t不是32位,所以我可以有条件地重新定义基本类型?

std::uint32_t类型定义为32位。此类型是可选定义的,如果您的平台没有32位无符号整数类型,则不可用。

你想要的代码是:

#if (typeid(std::uint32_t) == typeid(unsigned long))
    typedef unsigned long Integer32;
#else 
    typedef std::uint32_t Integer32;

这是不合法的,但你想说的是,换句话说,"如果uint32_t意味着unsigned long,那么Integer32意味着unsigned long。否则,它表示uint32_t的含义。

相当于:

typedef std::uint32_t Integer32;

因为在这两种情况下,您将Integer32混叠为与uint32_t表示相同的类型。那就写下来吧

保证uint32_t在符合标准的实现中是无符号32位类型。既然它不是unsigned long在你的实现,那么它几乎肯定是unsigned int。这两种类型,unsigned longunsigned int,是不同的类型,即使它们大小相同。相比之下,uint32_t是一个类型定义,所以它的类型与它的类型定义是相同的。

回答你的新问题:

typedef unsigned short Integer16;

unsigned short可能不完全是16位(尽管没有很多实现不是这样)。如果你想要一个精确的16位无符号类型,那么这就是uint16_t的作用。它是一个可选的类型,所以如果没有一个合适的类型,你的代码将导致一个信息错误,这几乎是你所能做的。

typedef std::uint32_t Integer32;

OK,警告uint32_t是可选类型。如果你喜欢Integer32这个名字,那么你可以自由地使用它。

typedef unsigned int FastInteger16;

如果你想要一个至少16位的快速无符号整数,使用std::uint_fast16_t而不是unsigned int

typedef unsigned long FastInteger32;

如果你想要一个至少32位的快速无符号整数,使用std::uint_fast32_t而不是unsigned long