💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
# ^ 运算符(C# 参考) 二元 **^** 运算符是为整型和 **bool** 类型预定义的。对于整型,**^** 将计算操作数的按位“异或”。对于 **bool** 操作数,**^** 将计算操作数的逻辑“异或”;也就是说,当且仅当只有一个操作数为 **true** 时,结果才为 **true**。 ## 备注 用户定义的类型可重载 **^** 运算符(请参见[运算符](https://msdn.microsoft.com/zh-CN/library/s53ehcz3.aspx))。 对于整数类型适用的运算对枚举类型通常也适用。 ``` class XOR { static void Main() { // Logical exclusive-OR // When one operand is true and the other is false, exclusive-OR // returns True. Console.WriteLine(true ^ false); // When both operands are false, exclusive-OR returns False. Console.WriteLine(false ^ false); // When both operands are true, exclusive-OR returns False. Console.WriteLine(true ^ true); // Bitwise exclusive-OR // Bitwise exclusive-OR of 0 and 1 returns 1. Console.WriteLine("Bitwise result: {0}", Convert.ToString(0x0 ^ 0x1, 2)); // Bitwise exclusive-OR of 0 and 0 returns 0. Console.WriteLine("Bitwise result: {0}", Convert.ToString(0x0 ^ 0x0, 2)); // Bitwise exclusive-OR of 1 and 1 returns 0. Console.WriteLine("Bitwise result: {0}", Convert.ToString(0x1 ^ 0x1, 2)); // With more than one digit, perform the exclusive-OR column by column. // 10 // 11 // -- // 01 // Bitwise exclusive-OR of 10 (2) and 11 (3) returns 01 (1). Console.WriteLine("Bitwise result: {0}", Convert.ToString(0x2 ^ 0x3, 2)); // Bitwise exclusive-OR of 101 (5) and 011 (3) returns 110 (6). Console.WriteLine("Bitwise result: {0}", Convert.ToString(0x5 ^ 0x3, 2)); // Bitwise exclusive-OR of 1111 (decimal 15, hexadecimal F) and 0101 (5) // returns 1010 (decimal 10, hexadecimal A). Console.WriteLine("Bitwise result: {0}", Convert.ToString(0xf ^ 0x5, 2)); // Finally, bitwise exclusive-OR of 11111000 (decimal 248, hexadecimal F8) // and 00111111 (decimal 63, hexadecimal 3F) returns 11000111, which is // 199 in decimal, C7 in hexadecimal. Console.WriteLine("Bitwise result: {0}", Convert.ToString(0xf8 ^ 0x3f, 2)); } } /* Output: True False False Bitwise result: 1 Bitwise result: 0 Bitwise result: 0 Bitwise result: 1 Bitwise result: 110 Bitwise result: 1010 Bitwise result: 11000111 */ ``` 在前面的示例中,0xf8 ^ 0x3f 的计算对以下两个二进制值(分别对应于十六进制值 F8 和 3F)执行按位“异或”运算: 1111 1000 0011 1111 “异或”运算的结果是 1100 0111,即十六进制值 C7。 ## 请参阅 [C# 参考](https://msdn.microsoft.com/zh-CN/library/618ayhy6.aspx) [C# 编程指南](https://msdn.microsoft.com/zh-CN/library/67ef8sbd.aspx) [C# 运算符](https://msdn.microsoft.com/zh-CN/library/6a71f45d.aspx)