简体   繁体   English

〜i真的等于i!= -1吗?

[英]Is ~i really equivalent to i != -1?

How does ~i work in C++? 如何~i的工作在C ++?

I just noticed it is equivalent to i != -1 , but I'm not certain about that. 我只是注意到它等于i != -1 ,但是我不确定。

int arr[3] {1, 2, 3};
int n = 3;
for (int i = n - 1; ~i; i--) {
    cout << arr[i] << ' ';
}

It printed the array in reverse. 它反向打印阵列。

~ is the bitwise NOT operator. ~是按位NOT运算符。 ~i is 0 if and only if i has 1 in all its bits. 当且仅当i所有位都为1时, ~i为0。 Whether -1 has all bits 1 depends on how signed numbers are represented on the system. -1是否具有所有位1取决于系统上符号号的表示方式。 In two's complement representation, -1 is represented with all bits 1, so on such systems ~(-1) == 0 . 在二进制补码表示中,-1用所有位1表示,因此在这样的系统~(-1) == 0 Neither in one's complement, nor in sign-and-magnitude does that hold true. 不论是在补语上,还是在符号和幅度上,都不成立。

Therefore, the answer is no; 因此,答案是否定的。 not on all systems. 并非在所有系统上。 That said, two's complement is fairly ubiquitous in modern machines (everything made since the 90's), and on such systems, the answer is yes. 就是说,在现代机器(自90年代以来的所有产品)中,二进制补码是相当普遍的,在这样的系统上,答案是肯定的。 Regardless of the sign representation however, i != -1 is much more readable. 但是,无论符号表示如何, i != -1都更具可读性。

~i is bitwise NOT operator. ~i是按位NOT运算符。 Ie it inverts every bit in i . 即,它使i每一点都反转。 -1 is represented binary as every bit of number being set to 1, inverting every bit to 0 gets you 0. And when checking integer in place where bool is expected 0 is treated as false and any other number as true . -1表示二进制,因为数字的每一位都设置为1,将每一位都反转为0会得到0。当在期望bool位置检查整数时,将0视为false并将任何其他数字视为true

So, in this particular case yes, ~i is equivalent with i != -1 . 因此,在这种特殊情况下, ~i等于i != -1

Because your i variable from for loop is of type int, which is defined as signed integer, and as such in twos complement, its binary representation of value -1 is all bits set, what means all bits are 1. On other side, bitwise negation of all ones is all zeros, and that is what you need, loop to execute until i>=0 or i!=-1, since you decrementing i. 因为for循环中的i变量是int类型的,其定义为有符号整数,并且因此以二进制补码形式表示,因此其值-1的二进制表示形式是所有位均置1,这意味着所有位均为1。全1的否定全为0,这就是您所需要的,因为您要递减i,所以循环执行直到i> = 0或i!=-1。 In that context of bitwise operations on sign values on system has twos complement binary representation of int, yes, it is the same. 在这种情况下,对系统上符号值的按位运算具有整数的二进制补码二进制表示形式,是的,它是相同的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM