C语言 波浪号(~)运算符有什么作用?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3952122/
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
What does tilde(~) operator do?
提问by fuddin
I recently saw the above operator in a code,I googled for it but found nothing.The code is below.Please describe what actually does this operator do?
我最近在一个代码中看到了上面的运算符,我用谷歌搜索但没有找到。代码在下面。请描述这个运算符实际上是做什么的?
#include<stdio.h>
int main()
{
unsigned long int i=0;
char ch;
char name1[20],name2[20];
FILE *fp,*ft;
printf("ENTER THE SOURCE FILE:");
gets(name1);
printf("ENTER THE DESTINATION FILE:");
gets(name2);
fp=fopen(name1,"r");
ft=fopen(name2,"w");
if(fp==NULL)
{
printf("CAN,T OPEN THE FILE");
}
while(!feof(fp))
{
ch=getc(fp);
ch=~((ch^i));/*<--Here*/
i+=2;
if(i==100000)
{
i=0;
}
putc(ch,ft);
}
fclose(fp);
fclose(ft);
return 0;
}
回答by In silico
The ~operator in C++ (and other C-like languages like C and Java) performs a bitwise NOT operation- all the 1 bits in the operand are set to 0 and all the 0 bits in the operand are set to 1. In other words, it creates the complementof the original number.
所述~在C运算符++(其他类C等C语言和Java语言)进行逐位NOT操作-中的所有操作数被设置为0,所有在操作数被设定为1。换言之0比特1个比特,它创建原始数字的补码。
For example:
例如:
10101000 11101001 // Original (Binary for -22,295 in 16-bit two's complement)
01010111 00010110 // ~Original (Binary for 22,294 in 16-bit two's complement)
In your example, ch=~((ch^i))performs a bitwise NOT on the bitwise XORof chand ithen assigns the result to ch.
在你的榜样,ch=~((ch^i))在执行按位非按位异或的ch和i,然后将结果分配ch。
The bitwise NOT operator has an interesting property that when applied on numbers represented by two's complement, it changes the number's sign and then subtracts one (as you can see in the above example).
按位 NOT 运算符有一个有趣的属性,当应用于由2 的补码表示的数字时,它会更改数字的符号,然后减去 1(如您在上面的示例中所见)。
You may want become familiar with the different operators of the C++ languagesince it is difficult to search for operators on search engines. Better yet, you can get a good C++ bookwhich will tell you about the C++ operators.
您可能希望熟悉C++ 语言的不同运算符,因为很难在搜索引擎上搜索运算符。更好的是,您可以获得一本很好的 C++ 书籍,它会告诉您有关 C++ 运算符的信息。
回答by JoshD
The ~ operator inverts all the bits. So 10000001becomes 01111110.
~ 运算符反转所有位。于是10000001变成01111110。
回答by Erkan Haspulat
It is the bitwise complement operator. Given the input
它是按位补码运算符。鉴于输入
010011101
010011101
returns the output:
返回输出:
101100010
101100010

