按位与、逻辑与操作和按位异或和逻辑异或操作(&,^)


&和^好长时间没有了,今天在看别人的代码的时候感觉这两个非常陌生,都忘了它们是干什么的啦,现在回顾一下,记录一下。

从msdn上找到相关信息,让我受益匪浅呀,先看一下^操作的代码:这个是msdn上的代码

    class XOR
{
static void Main()
{
// 逻辑异或

// 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);


// 按位异或(将两个数字转换为二进制后,相同的位置上相比较,如果相同得到的结果为0,否则为一)

// 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
*/


然后看看按位与和逻辑与的代码:

class BitwiseAnd
{
static void Main()
{
        //与操作是对整形和布尔型而言的,整形就是按位与,布尔型就是逻辑与,与操作跟异或操作刚好相反,这边都不做详细介绍了。
Console.WriteLine(true & false); // 逻辑与
Console.WriteLine(true & true); // logical and
Console.WriteLine("0x{0:x}", 0xf8 & 0x3f); // 按位与 }
}
/*
Output:
False
True
0x38
*/

 更多运算符的详细,可以查看msdn的网站:http://msdn.microsoft.com/zh-cn/library/6a71f45d.aspx

原文地址:https://www.cnblogs.com/aptdo2008/p/2258474.html