简体   繁体   English

〜运算符的功能是什么?

[英]What is the function of the ~ operator?

Unfortunately, search engines have failed me using this query. 不幸的是,搜索引擎使我无法使用此查询。

For instance: 例如:

int foo = ~bar;

在C和C ++中,它是一个按位NOT

I'm assuming based on your most active tags you're referring to C#, but it's the same NOT operator in C and C++ as well. 我假设你基于最活跃的标签,你指的是C#,但它也是C和C ++中的同一个NOT运算符。

From MSDN : 来自MSDN

The ~ operator performs a bitwise complement operation on its operand, which has the effect of reversing each bit. 〜运算符对其操作数执行按位补码运算,具有反转每个位的效果。 Bitwise complement operators are predefined for int, uint, long, and ulong. 为int,uint,long和ulong预定义了按位补码运算符。

Example program: 示例程序:

static void Main() 
{
    int[] values = { 0, 0x111, 0xfffff, 0x8888, 0x22000022};
    foreach (int v in values)
    {
        Console.WriteLine("~0x{0:x8} = 0x{1:x8}", v, ~v);
    }
}

Output: 输出:

~0x00000000 = 0xffffffff
~0x00000111 = 0xfffffeee
~0x000fffff = 0xfff00000
~0x00008888 = 0xffff7777
~0x22000022 = 0xddffffdd

它被称为Tilde (用于将来的搜索),通常是按位NOT的用户(即每个位的补码)

它被称为代字号,看起来有些语言使用它作为一个按位NOT: http//en.wikipedia.org/wiki/Tilde#Computer_languages

Normally it's the Negation operator. 通常它是Negation运算符。 What is the Language? 什么是语言?

bitwise negation , yields the bitwise complement of the operand. 按位 ,产生操作数的按位补码。

In many programming languages (including those in the C family), the bitwise NOT operator is "~" (tilde). 在许多编程语言(包括C系列中的编程语言)中,按位NOT运算符是“〜”(代字号)。 This operator must not be confused with the "logical not" operator, "!" 不得将此运算符与“逻辑非”运算符混淆,“!” (exclamation point), which in C++ treats the entire value as a single Boolean—changing a true value to false, and vice versa, and that C makes a value of 0 to 1 and a value other than 0 to 0. The "logical not" is not a bitwise operation. (感叹号),在C ++中将整个值视为单个布尔值 - 将true值更改为false,反之亦然,并且C的值为0到1,值为0到0之外的值。不是“不是一个按位操作。

In C, it's the bitwise complement operator . 在C中,它是按位补码运算符 Basically, it looks at the binary representation of a number and converts the ones into zeros and the zeros into ones. 基本上,它查看数字的二进制表示,并将其转换为零,将零转换为1。

In most C-like languages, it is a bitwise not. 在大多数类C语言中,它不是一点点。 This will take the raw binary implementation of a number, and change all 1's to 0's and 0's to 1's. 这将采用数字的原始二进制实现,并将所有1改为0,将0改为1。

For example: 例如:

ushort foo = 42;   // 0000 0000 0010 1010
ushort bar = ~foo; // 1111 1111 1101 0101
Console.WriteLine(bar); // 65493

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

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