Earn More by Sharing What You Love
Do you create content for developers working with .NET, C#, Java, Python, or Node.js? Turn your expertise into extra income!

Tim Corey
4m 48s
C# 中的二进制操作对于在位级工作、优化性能以及理解数据的存储和操作方式至关重要。 其中一个重要的运算符是二进制 NOT (~),它可以翻转数字的所有位。 为了深入了解这一点,让我们一起回顾一下 Tim Corey 的视频"C#中的二进制:二进制 NOT 操作符,10 分钟以内"。
Tim Corey 首先解释说,本视频是关于理解 C# 中二进制的系列视频的一部分。 本课是该系列的第七课,主要介绍二进制 NOT 运算符 (~)。 他强调,这将是一堂快速课,时间控制在十分钟以内,使其易于理解和掌握。
Tim 调整了启动代码,以提高可读性。 他没有手动格式化二进制值,而是在末尾使用了冒号(:)和变量名,以确保清晰。 这样,数值的二进制表示法就会保留在开头,从而便于比较。
他首先声明了一个整数变量:
// Declare an integer variable and assign it the value of 1.
int value = 1;' Declare an integer variable and assign it the value of 1.
Dim value As Integer = 1这就设置了一个可以应用 NOT 运算符的简单场景。
Tim 介绍了 ~ 运算符并演示了其语法:
// Apply the Binary NOT operator to flip all bits of the integer 'value'.
int notValue = ~value;' Apply the Binary NOT operator to flip all bits of the integer 'value'.
Dim notValue As Integer = Not value他指出,在大多数键盘上,Tilde (~) 位于左上角,Escape 键的下方,1 键的旁边。 他澄清说,这与感叹号(!)不同,后者通常被称为 "Bang 字符"。转折号执行位否定,而感叹号用于逻辑否定。
Tim 解释说,NOT 运算符会翻转数字二进制表示法中的所有位。 这意味着:
对一个数字应用 ~ 可以得到它的位补码。 他复制了控制台输出以观察结果。
Tim 运行了程序,并指出结果比预期的要长很多。 例如,如果 value = 1,输出就不只是 0,而是一个更长的 1 序列,其后是翻转位。 他指出 ~1 的结果是
// Observed output for ~1
11111111111111111111111111111110' Observed output for ~1
11111111111111111111111111111110为什么会出现这种情况?
Tim 解释说,出现这种行为是因为 C# 使用了 32 位有符号整数(int)。 由于 C# 中的 int 实际上是 Int32,它由 32 位组成。 在执行 NOT 操作时,所有 32 位都要翻转,而不仅仅是 1 的单位表示。
为了更清楚地说明这一点,他调整了输出格式,明确显示 32 位:
// Convert the result of the NOT operation to a binary string representation,
// pad it to 32 bits, and print it.
Console.WriteLine(Convert.ToString(notValue, 2).PadLeft(32, '0'));' Convert the result of the NOT operation to a binary string representation,
' pad it to 32 bits, and print it.
Console.WriteLine(Convert.ToString(notValue, 2).PadLeft(32, "0"c))这将显示完整的二进制表示法,从而更容易看到所有比特是如何翻转的。
在这一点上,Tim 提出了一个问题:为什么 NOT 运算符会有用? 他暗示,在使用其他位运算时,位运算的价值会更加明显,例如
Tim 强调,在学习更复杂的二进制操作之前,了解 NOT 等基础概念非常重要。 他向观众保证,一旦他们掌握了二进制操作,就会发现这些操作是多么强大和高效。 二进制操作允许开发人员
最后,Tim 还暗示了下一课的内容,即使用 NOT 运算符和其他位运算技术清除特定位。 他强调,掌握这些基础知识对于有效使用 C# 中的二进制工作至关重要。
Tim Corey 对 C# 中的二进制 NOT 操作符进行了清晰实用的解释。 通过翻转数字的所有位,~ 是在位级工作的基本工具。 了解该运算符可为更高级的二进制操作(如位屏蔽和位移)奠定基础。 如果您正在潜心研究底层编程或优化性能,这是一个需要掌握的重要概念。
有关更多见解,请查看 Tim Corey 的完整视频和他的 C# 二进制系列!
Do you create content for developers working with .NET, C#, Java, Python, or Node.js? Turn your expertise into extra income!
Join our newsletter, you’ll get exclusive access on article updates. We value your privacy