The OR operator combines all the set bits in both values into a third value. The AND operator returns another number that contains a 1 where each of the two numbers also have a 1.
To understand bitwise operators, we look at patterns of bits. Bitwise operators are essential for some programs that manipulate bit flags.
To start, we look at the numbers 77 and 100. These are represented with bit patterns. We combine two values with bitwise OR, and print the result.
using System; class Program { static void Main() { int a = 77; int b = 100; // Use bitwise OR. int c = a | b; // Display bits. Console.WriteLine("{0} = {1}", GetIntBinaryString(a), a); Console.WriteLine("{0} = {1}", GetIntBinaryString(b), b); Console.WriteLine("{0} = {1}", GetIntBinaryString(c), c); } static string GetIntBinaryString(int value) { return Convert.ToString(value, 2).PadLeft(32, '0'); } }00000000000000000000000001001101 = 77 00000000000000000000000001100100 = 100 00000000000000000000000001101101 = 109
This program generates 2 random numbers. It then uses bitwise "and" on them. Next a helper method is invoked, and we write the bit values to the screen.
using System; class Program { static void Main() { int value1 = 555; int value2 = 7777; // Use bitwise and operator. int and = value1 & value2; // Display bits. Console.WriteLine(GetIntBinaryString(value1)); Console.WriteLine(GetIntBinaryString(value2)); Console.WriteLine(GetIntBinaryString(and)); } static string GetIntBinaryString(int value) { return Convert.ToString(value, 2).PadLeft(32, '0'); } }00000000000000000000001000101011 00000000000000000001111001100001 00000000000000000000001000100001
Data structures often use bit flags on their nodes. In certain algorithms, you quickly combine nodes on the stack by using the bitwise OR operator.
Data structures such as digital trees use bitmasks to store information. If you take 2 nodes in the tree, you can use the bitwise and to compare the data in their bitmasks.
We looked at the bitwise OR and AND operators. These operators help with data structures and algorithms where storage space must be compressed into bit masks.