[英]Purpose of casting -1 to uint32?
This is probably a really silly question to experienced C++ developers, but what is the purpose of casting a -1 to uint32? 对于有经验的C ++开发人员来说,这可能是一个非常愚蠢的问题,但是将-1转换为uint32的目的是什么? I am translating a program from C++ to C# and there are many occasions when I see something like this:
我正在将一个程序从C ++翻译成C#,在很多场合我看到这样的东西:
static const uint32 AllTypes = static_cast<uint32>(-1);
What exactly does this do? 这到底是做什么的? How can the same be accomplished in C#?
如何在C#中实现同样的目标?
On systems using two's complement, casting -1
to unsigned gives the highest value an unsigned number can represent. 在使用二进制补码的系统上,将
-1
为无符号表示无符号数表示的最高值。
In C# you can use unchecked((UInt32)-1)
or better: UInt32.MaxValue
. 在C#中,您可以使用
unchecked((UInt32)-1)
或更好: UInt32.MaxValue
。 This is well defined behavior, and works on all CPU architectures. 这是明确定义的行为,适用于所有CPU架构。
According to the thread rve linked , casting -1
to unsigned results in all bits being set on all architectures in C++. 根据线程rve链接 ,将
-1
为无符号会导致在C ++中的所有体系结构上设置所有位。
如何在C#中完成同样的事情
uint AllTypes = uint.MaxValue;
I guess it's used to have all bits to 1. Useful when we use tagged data. 我想它已经习惯了将所有位都设置为1.当我们使用标记数据时很有用。 Probably each elementary type it's given a bit, and 'complex' types (arrays, for instance) get their own.
可能每种基本类型都有一些,而“复杂”类型(例如数组)可以得到它们自己的类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.