C++ 中的 Uint32 和 unsigned int 有什么区别?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14911813/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 18:48:33  来源:igfitidea点击:

What is the difference between an Uint32 and an unsigned int in C++?

c++types

提问by user1511417

Is it the same? If no: what is the difference? If yes then why do you need this type?

是一样的吗?如果不是:有什么区别?如果是,那么你为什么需要这种类型?

回答by Matteo Italia

uint32_t(or however pre-C++11 compilers call it) is guaranteed to be a 32-bit unsigned integer; unsigned intis whatever unsigned integer the compiler likes best to call unsigned int, as far as it meets the requirements of the standard (which demands for it a 0-65535 minimum range).

uint32_t(或者无论 C++11 之前的编译器如何称呼它)保证是 32 位无符号整数;unsigned int是编译器最喜欢调用的任何无符号整数unsigned int,只要它满足标准的要求(要求它的最小范围为 0-65535)。

Like int, unsigned inttypically is an integer that is fast to manipulate for the current architecture (normally it fits into a register), so it's to be used when a "normal", fast integer is required.

int,unsigned int通常是一个整数,可以快速处理当前体系结构(通常它适合寄存器),因此在需要“正常”、快速整数时使用它。

uint32_t, instead, is used when you need an exact-width integer, e.g. to serialize to file, or when you require that exact range or you rely on unsigned overflow to happen exactly at 2^32-1.

uint32_t,相反,当你需要一个精确宽度的整数时使用,例如序列化到文件,或者当你需要那个精确范围或你依赖无符号溢出恰好发生在2^32-1

For example, on a 16 bit-processor unsigned intwill typically be 16 bits wide, while uint32_twill haveto be 32 bits wide.

例如,在一个16位的处理器unsigned int将典型地是16个比特宽,而uint32_t具有成为32个位宽。



Incidentally, as pointed out by @Marc Glisse, while unsigned intis always present, uint32_tis not mandatory - a particular compiler implementation may not provide it. This is mostly because not all platforms can easily provide such a type (typically DSPs with weird word sizes).

顺便说一句,正如@Marc Glisse所指出的,虽然unsigned int始终存在,但uint32_t不是强制性的 - 特定的编译器实现可能不提供它。这主要是因为并非所有平台都可以轻松提供这种类型(通常是具有奇怪字长的 DSP)。