波浪号(~)运算符有什么作用? [英] What does tilde(~) operator do?

查看:28
本文介绍了波浪号(~)运算符有什么作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近在一个代码中看到了上面的操作符,我google了一下,没有找到.代码如下.请描述这个操作符实际上是做什么的?

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

推荐答案

C++(以及其他类似 C 的语言,如 C 和 Java)中的 ~ 运算符执行 按位非运算 - 操作数中的所有 1 位都设置为 0,操作数中的所有 0 位都设置为1. 换句话说,它创建了原始数字的补码.

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.

例如:

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)

在您的示例中, ch=~((ch^i))按位异或 然后将结果分配给 ch.

In your example, ch=~((ch^i)) performs a bitwise NOT on the bitwise XOR of ch and i then assigns the result to ch.

按位 NOT 运算符有一个有趣的属性,当应用于由 two's Complement,它会改变数字的符号,然后减一(如上例所示).

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

您可能想熟悉 C++ 语言的不同运算符,因为很难在搜索引擎上搜索运营商.更好的是,您可以获得一本不错的 C++ 书籍,它会告诉您关于 C++ 运算符.

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.

这篇关于波浪号(~)运算符有什么作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆