TheDeveloperBlog.com


C# Bitwise Or

Bitwise OR combines set bits. With "or", you can combine all the set bits in both values into a third value returned by the operator. And this is essential for some programs that manipulate bit flags.


Example. To start, we look at the numbers 77 and 100. These are represented with bit patterns. When these two values are combined with bitwise OR all of the bits that are 1 in either or both values are 1 in the result. The rest of the bits are 0.

C# program that shows bitwise or

using System;

class Program
{
    static void Main()
    {
	int a = 77;
	int b = 100;
	int c = a | b;

	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 n)
    {
	char[] b = new char[32];
	int pos = 31;
	int i = 0;

	while (i < 32)
	{
	    if ((n & (1 << i)) != 0)
	    {
		b[pos] = '1';
	    }
	    else
	    {
		b[pos] = '0';
	    }
	    pos--;
	    i++;
	}
	return new string(b);
    }
}

Output

00000000000000000000000001001101 = 77
00000000000000000000000001100100 = 100
00000000000000000000000001101101 = 109


Discussion. Memory-efficient 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. The result indicates all the bits set by at least one of the nodes.

Tip: This can yield amazing performance improvements in rare situations. Most algorithms do not benefit.


Summary. We looked at the bitwise OR operator in the C# language. This is a binary operator because it acts upon two operands in an expression and pushes one result to the evaluation stack.

Also: Check out the bitwise XOR operator for an exclusive OR, which is useful in other rare programs.

XOR