为什么(18446744073709551615 == -1)是正确的? [英] Why is (18446744073709551615 == -1) true?
问题描述
在处理 string :: npos
时,我注意到了一些东西,但在网络上找不到任何解释。
When I was working on string::npos
I noticed something and I couldn't find any explanation for it on the web.
(string::npos == ULONG_MAX)
和
(string::npos == -1)
是真的。
所以我尝试了这个: / p>
So I tried this:
(18446744073709551615 == -1)
这也是事实。
怎么可能?
推荐答案
18,446,744,073,709,551,615
提到的这个数字 18,446,744,073,709,551,615
实际上是 2 ^ 64 − 1
。这里重要的是 2 ^ 64-1
本质上是基于0的 2 ^ 64
。无符号整数的第一位数字是 0
,而不是 1
。因此,如果最大值为 1
,则有两个可能的值: 0
或 1
(2)。
18,446,744,073,709,551,615
This number mentioned, 18,446,744,073,709,551,615
, is actually 2^64 − 1
. The important thing here is that 2^64-1
is essentially 0-based 2^64
. The first digit of an unsigned integer is 0
, not 1
. So if the maximum value is 1
, it has two possible values: 0
, or 1
(2).
让我们看看64位二进制文件中的 2 ^ 64-1
,所有位都打开。
Let's look at 2^64 - 1
in 64bit binary, all the bits are on.
1111111111111111111111111111111111111111111111111111111111111111b
-1
让我们看看 +1
64位二进制文件。
The -1
Let's look at +1
in 64bit binary.
0000000000000000000000000000000000000000000000000000000000000001b
要使其在一个人的补语(OCP)中为负,我们将这些位取反。
To make it negative in One's Complement (OCP) we invert the bits.
1111111111111111111111111111111111111111111111111111111111111110b
计算机很少使用OCP,它们使用补码(TCP)。要获取TCP,请向OCP添加一个。
Computers seldom use OCP, they use Two's Complement (TCP). To get TCP, you add one to OCP.
1111111111111111111111111111111111111111111111111111111111111110b (-1 in OCP)
+ 1b (1)
-----------------------------------------------------------------
1111111111111111111111111111111111111111111111111111111111111111b (-1 in TCP)
但是,等一下,您问,如果补码 -1
是,
"But, wait" you ask, if in Twos Complement -1
is,
1111111111111111111111111111111111111111111111111111111111111111b
并且,如果为二进制 2 ^ 64-1
是
1111111111111111111111111111111111111111111111111111111111111111b
然后它们是相等的!而且,这就是您所看到的。您正在将有符号的64位整数与无符号的64位整数进行比较。在C ++中,这意味着将有符号的值转换为无符号,编译器会这样做。
Then they're equal! And, that's what you're seeing. You're comparing a signed 64 bit integer to an unsigned 64bit integer. In C++ that means convert the signed value to unsigned, which the compiler does.
对于技术更正感谢评论中的davmac ,从 -1
的转换实际上是在语言中指定了 signed
unsigned 类型,而不是该函数的建筑。话虽如此,您可能会发现上面的答案对于理解支持两个人称赞但缺乏确保您可以依靠的结果的规范的语言很有帮助。
For a technical correction thanks to davmac in the comments, the conversion from -1
which is signed
to an unsigned
type of the same size is actually specified in the language, and not a function of the architecture. That all said, you may find the answer above useful for understanding the arch/languages that support two's compliment but lack the spec to ensure results you can depend on.
这篇关于为什么(18446744073709551615 == -1)是正确的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!