Bitwise OrUse the bitwise OR operator and learn how it changes an int.
This page was last reviewed on Nov 8, 2023.
Bitwise OR. This operator combines all the set bits in both values into a third value. To understand bitwise operators, we look at patterns of bits.
Operator notes. This operator is essential for some programs that manipulate bit flags. But in most C# programs, we do not need to use bitwise operators.
Bitwise XOR
Input and output. Consider this table that shows some possible bit changes from bitwise OR. We see that if both or one operand has a bit, the result is 1.
Operand 1: 101 (Operator = |) Operand 2: 100 Result: 101
Example. 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.
Result All of the bits that are 1 in either or both values are 1 in the result. The rest of the bits are 0.
Binary Representation
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); } }
00000000000000000000000001001101 = 77 00000000000000000000000001100100 = 100 00000000000000000000000001101101 = 109
Discussion. 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.
And The result of using bitwise "OR" 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.
A summary. We looked at the bitwise OR operator. This is a binary operator because it acts upon two operands in an expression and pushes one result to the evaluation stack.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Nov 8, 2023 (edit).
© 2007-2024 Sam Allen.