Csharp/CSharp Tutorial/Data Type/Bitwise AND
bitwise AND
<source lang="csharp">class MainClass {
public static void Main() { byte byte1 = 0x9a; // binary 10011010, decimal 154 byte byte2 = 0xdb; // binary 11011011, decimal 219 byte result; System.Console.WriteLine("byte1 = " + byte1); System.Console.WriteLine("byte2 = " + byte2); result = (byte) (byte1 & byte2); System.Console.WriteLine("byte1 & byte2 = " + result); }
}</source>
byte1 = 154 byte2 = 219 byte1 & byte2 = 154
Use bitwise AND to determine if a number is odd.
<source lang="csharp">using System;
class Example {
public static void Main() { ushort num; num = 10; if((num & 1) == 1) Console.WriteLine("This won"t display."); num = 11; if((num & 1) == 1) Console.WriteLine(num + " is odd."); }
}</source>
11 is odd.
Use bitwise AND to make a number even
<source lang="csharp">using System;
class Example {
public static void Main() { ushort num; ushort i; for(i = 1; i <= 10; i++) { num = i; Console.WriteLine("num: " + num); num = (ushort) (num & 0xFFFE); // num & 1111 1110 Console.WriteLine("num after turning off bit zero: " + num + "\n"); } }
}</source>
num: 1 num after turning off bit zero: 0 num: 2 num after turning off bit zero: 2 num: 3 num after turning off bit zero: 2 num: 4 num after turning off bit zero: 4 num: 5 num after turning off bit zero: 4 num: 6 num after turning off bit zero: 6 num: 7 num after turning off bit zero: 6 num: 8 num after turning off bit zero: 8 num: 9 num after turning off bit zero: 8 num: 10 num after turning off bit zero: 10