且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

波浪号(〜)运算符的作用是什么?

更新时间:2023-02-16 16:04:42

运算符执行按位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> 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.