简体   繁体   English

波浪号(~)运算符有什么作用?

[英]What does tilde(~) operator do?

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;
}       

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 complement of the original number. C++(以及其他类似 C 的语言,如 C 和 Java)中的~运算符执行按位非操作- 操作数中的所有 1 位都设置为 0,操作数中的所有 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 XOR of ch and i then 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 运算符有一个有趣的属性,当应用于由二进制补码表示的数字时,它会更改数字的符号,然后减去 1(如您在上面的示例中所见)。

You may want become familiar with the different operators of the C++ language since it is difficult to search for operators on search engines.您可能希望熟悉C++ 语言的不同运算符,因为很难在搜索引擎上搜索运算符。 Better yet, you can get a good C++ book which will tell you about the C++ operators.更好的是,您可以获得一本很好的 C++ 书籍,它会告诉您有关 C++ 运算符的信息。

The ~ operator inverts all the bits. ~ 运算符反转所有位。 So 10000001 becomes 01111110 .所以10000001变成01111110

It is the bitwise complement operator.它是按位补码运算符。 Given the input鉴于输入

010011101 010011101

returns the output:返回输出:

101100010 101100010

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

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