| [ directory ] |
|
8.3 Bitwise OperatorsBitwise operators are used for conducting bit operations. C# and Java provide a common set of bit operators, which are discussed in the following sections. 8.3.1 The & OperatorBinary & operators are predefined for the integral types and bool. For integral types, & computes the bitwise AND of its operands. For bool operands, & computes the logical AND of its operands; that is, the result is true if and only if both its operands are true. This operator can be overloaded. 8.3.2 The | OperatorBinary | operators are predefined for the integral types and bool. For integral types, | computes the bitwise OR of its operands. For bool operands, | computes the logical OR of its operands; that is, the result is false if and only if both its operands are false. This operator can be overloaded. 8.3.3 The ^ OperatorBinary ^ operators are predefined for the integral types and bool. For integral types, ^ computes the bitwise exclusive-OR of its operands. For bool operands, ^ computes the logical exclusive-OR of its operands; that is, the result is true if and only if exactly one of its operands is true. This operator can be overloaded. 8.3.4 The ~ OperatorThe ~ operator performs a bitwise complement operation on its operand. Bitwise complement operators are predefined for int, uint, long, and ulong. This operator can be overloaded. Listing 8.3 shows the bitwise operations. Listing 8.3 Bitwise Operations (C#)
using System;
public class BitWise {
public static void Main(string[] args) {
int a = 2;
int b = 3;
//Integral types
Console.WriteLine("a = 2, b= 3 and a | b ="+(a| b));
Console.WriteLine("a = 2, b= 3 and a & b ="+( a & b));
Console.WriteLine("a = 2, b= 3 and a ^ b ="+(a ^ b));
Console.WriteLine("a = 2 and ~a ="+ (a));
bool x = true;
bool y = false;
//Bool types
Console.WriteLine("x = true, y= false and x | y ="+(x | y));
Console.WriteLine("x = true, y= false and x & y ="+(x & y));
Console.WriteLine("x = true, y= false and x ^ y ="+(x ^ y));
}
}
The output of Listing 8.3 is as follows: a = 2, b= 3 and a | b =3 a = 2, b= 3 and a & b =2 a = 2, b= 3 and a ^ b =1 a = 2 and ~ a =-3 x = true, y= false and x | y True x = true, y= false and x & y =False x = true, y= false and x ^ y True The C# bitwise operators function similarly to their Java equivalents. |
| [ directory ] |
|