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

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

问题描述

最近我在代码中看到了上述运算符,我用谷歌搜索了一下,但没有发现。下面的代码。请说明该运算符的实际作用是什么?

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


推荐答案

运算符执行按位NOT操作-操作数中的所有1位都设置为0,操作数中的所有0位都设置为1。换句话说,它会创建 complement

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 和<$ c $的按位XOR c> 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运算符具有利益ng属性,当应用于二进制补码表示的数字时,它会更改数字的符号,然后减去一个(如上例所示)。

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天全站免登陆