uint32_t如何保证32位?

How does uint32_t guarantee 32 bits?

在大多数实现中,我看到 uint32_t 定义为

typedef unsigned int uint32_t;

但据我了解,ints 在所有系统中都是 not always guaranteed to be 4 bytes。那么如果系统有非4字节整数,uint32_t如何保证4?

uint32_t guarantee 32 bits?

是的。


如果 CHAR_BIT == 16uint32_t 将是 2 "bytes"。 A "byte" 在 C 中并不总是 8 位

int 的大小不是实现 uintN_t 的主要问题。

uintN_t (N = 8,16,32,64) 是可选的非填充类型,它们在系统支持时独立存在。发现它们的实现非常普遍,尤其是较大的。

intN_t 同样是可选的,必须是 2 的补码。

需要实施才能正确定义 uint32_t(如果不可能,则根本不定义)。

如果unsigned int满足要求(32位宽,无填充位),实现可以定义为

typedef unsigned int uint32_t;

如果不满足,但是unsigned long满足要求,可以定义为:

typedef unsigned long uint32_t;

或者如果合适的话,它可以使用不同的无符号类型。

<stdint.h> header 必须与其使用的编译器兼容。如果你采用无条件将 uint32_t 定义为 unsigned int<stdint.h> header,并将其与使 unsigned int 成为 16 位的编译器一起使用,结果将是non-conforming 实施。

可以通过为编译器定制 header 或编写 header 使其适应编译器的特性来保持兼容性。

作为一名程序员,您不必担心如何 保持正确性(当然好奇也没有错)。您可以相信它会正确完成——或者您可以向提供商投诉一个严重的错误。

每个定义 uint32_t 的 C 或 C++ 实现都以适用于该实现的方式定义它。仅当 unsigned int 满足该实现中的 uint32_t 时,它才可以使用 typedef unsigned int uint32_t;

在一个 C 或 C++ 实现中 typedef unsigned int uint32_t; 出现在 <stdint.h> 中这一事实并不意味着它将出现在任何其他 C 或 C++ 实现的 <stdint.h> 中。 unsigned int 不适合 uint32_t 的实现必须提供不同的 <stdint.h><stdint.h> 是实施的一部分,并在实施发生变化时发生变化。