开发者

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.

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.

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).

You may want become familiar with the different operators of the C++ language since it is difficult to search for operators on search engines. Better yet, you can get a good C++ book which will tell you about the C++ operators.


The ~ operator inverts all the bits. So 10000001 becomes 01111110.


It is the bitwise complement operator. Given the input

010011101

returns the output:

101100010

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜