C# Tutorial C# Advanced C# References

C# - Bitwise OR and assignment operator



The Bitwise OR and assignment operator (|=) assigns the first operand a value equal to the result of Bitwise OR operation of two operands.

(x |= y) is equivalent to (x = x | y)

The Bitwise OR operator (|) is a binary operator which takes two bit patterns of equal length and performs the logical OR operation on each pair of corresponding bits. It returns 1 if either or both bits at the same position are 1, else returns 0.

Bit_1Bit_2Bit_1 | Bit_2
000
101
011
111

The example below describes how bitwise OR operator works:

50 | 25 returns 59

     50    ->    110010  (In Binary)
   | 25    ->  | 011001  (In Binary)
    ----        --------
     59    <-    111011  (In Binary)  

The code of using Bitwise OR operator (|) is given below:

using System;

class MyProgram {
  static void Main(string[] args) {
    int x = 50;
    int y = 25;

    //Bitwise OR and assignment operation
    x |= y;

    //Displaying the result
    Console.WriteLine("x = "+x);
  }
}

The output of the above code will be:

x = 59

Example: Find largest power of 2 less than or equal to given number

Consider an integer 1000. In the bit-wise format, it can be written as 1111101000. However, all bits are not written here. A complete representation will be 32 bit representation as given below:

00000000000000000000001111101000  

Performing N |= (N>>i) operation, where i = 1, 2, 4, 8, 16 will change all right side bit to 1. When applied on 1000, the result in 32 bit representation is given below:

00000000000000000000001111111111 

Adding one to this result and then right shifting the result by one place will give largest power of 2 less than or equal to 1000.

00000000000000000000001000000000 

The below code will calculate the largest power of 2 less than or equal to given number.

using System;

class MyProgram {
  static int MaxPowerOfTwo(int N) {
    //changing all right side bits to 1.
    N |= (N>>1);
    N |= (N>>2);
    N |= (N>>4);
    N |= (N>>8);
    N |= (N>>16);
    
    //adding 1 to N makes smallest power
    //of 2 greater than given number
    N += 1;

    //right shift by one position makes
    //largest power of 2 less than or 
    //equal to given number
    N >>= 1;
    
    return N;
  }

  static void Main(string[] args) {
    Console.WriteLine("MaxPowerOfTwo(100) = "+
        MaxPowerOfTwo(100));
    Console.WriteLine("MaxPowerOfTwo(500) = "+
        MaxPowerOfTwo(500));
    Console.WriteLine("MaxPowerOfTwo(1000) = "+
        MaxPowerOfTwo(1000));      
  }
}

The above code will give the following output:

MaxPowerOfTwo(100) = 64
MaxPowerOfTwo(500) = 256
MaxPowerOfTwo(1000) = 512

❮ C# - Operators