Home C# Bitwise operators in C# tutorials

Bitwise operators in C# tutorials

Bitwise operators in C# allow you to manipulate individual bits within integer types, such as int, uint, long, ulong, byte, and sbyte.

They are commonly used in low-level programming, data compression, cryptography, and optimization tasks.

In this tutorial, we’ll cover:

1. Overview of Bitwise Operators

Here’s a quick overview of bitwise operators in C#:

Operator Description Example
& Bitwise AND a & b
` ` Bitwise OR
^ Bitwise XOR (exclusive OR) a ^ b
~ Bitwise NOT (one’s complement) ~a
<< Left shift a << n
>> Right shift a >> n

These operators work at the bit level, so they are used primarily with integer types in C#.

2. Bitwise AND (&)

The & (AND) operator compares each bit of its operands. It returns 1 if both bits are 1; otherwise, it returns 0.

Example:

using System;

public class BitwiseAndExample
{
    public static void Main()
    {
        int a = 6;  // Binary: 110
        int b = 3;  // Binary: 011

        int result = a & b; // Result: 2 (Binary: 010)

        Console.WriteLine("a & b = " + result);
    }
}

Explanation:

  • 6 in binary is 110.
  • 3 in binary is 011.
  • 6 & 3 results in 010 (binary for 2) because only the second bit from the right has both bits as 1.

Output:

a & b = 2

3. Bitwise OR (|)

The | (OR) operator compares each bit of its operands. It returns 1 if at least one of the bits is 1; otherwise, it returns 0.

Example:

using System;

public class BitwiseOrExample
{
    public static void Main()
    {
        int a = 6;  // Binary: 110
        int b = 3;  // Binary: 011

        int result = a | b; // Result: 7 (Binary: 111)

        Console.WriteLine("a | b = " + result);
    }
}

Explanation:

  • 6 in binary is 110.
  • 3 in binary is 011.
  • 6 | 3 results in 111 (binary for 7) because each bit position has at least one 1.

Output:

a | b = 7

4. Bitwise XOR (^)

The ^ (XOR) operator compares each bit of its operands. It returns 1 if the bits are different; otherwise, it returns 0.

Example:

using System;

public class BitwiseXorExample
{
    public static void Main()
    {
        int a = 6;  // Binary: 110
        int b = 3;  // Binary: 011

        int result = a ^ b; // Result: 5 (Binary: 101)

        Console.WriteLine("a ^ b = " + result);
    }
}

Explanation:

  • 6 in binary is 110.
  • 3 in binary is 011.
  • 6 ^ 3 results in 101 (binary for 5) because only the bits in each position differ.

Output:

a ^ b = 5

5. Bitwise NOT (~)

The ~ (NOT) operator inverts each bit of its operand, turning 1s to 0s and 0s to 1s. This is known as a bitwise complement.

Example:

using System;

public class BitwiseNotExample
{
    public static void Main()
    {
        int a = 6;  // Binary: 0000 0110 (32-bit integer representation)

        int result = ~a; // Result: -7 (Binary: 1111 1001 for signed int)

        Console.WriteLine("~a = " + result);
    }
}

Explanation:

  • 6 in binary is 0000 0110.
  • ~6 inverts the bits, resulting in 1111 1001, which is -7 in a signed integer representation due to two's complement notation.

Output:

~a = -7

6. Left Shift (<<) and Right Shift (>>)

The shift operators move the bits to the left or right by a specified number of positions.

  • Left Shift (<<): Shifts bits to the left, filling the rightmost bits with zeros.
  • Right Shift (>>): Shifts bits to the right, filling the leftmost bits with the sign bit (for signed types).

Example: Left Shift

using System;

public class LeftShiftExample
{
    public static void Main()
    {
        int a = 3; // Binary: 0000 0011

        int result = a << 2; // Result: 12 (Binary: 0000 1100)

        Console.WriteLine("a << 2 = " + result);
    }
}

Explanation:

  • 3 in binary is 0000 0011.
  • Shifting left by 2 positions results in 0000 1100 (binary for 12).

Output:

a << 2 = 12

Example: Right Shift

using System;

public class RightShiftExample
{
    public static void Main()
    {
        int a = 12; // Binary: 0000 1100

        int result = a >> 2; // Result: 3 (Binary: 0000 0011)

        Console.WriteLine("a >> 2 = " + result);
    }
}

Explanation:

  • 12 in binary is 0000 1100.
  • Shifting right by 2 positions results in 0000 0011 (binary for 3).

Output:

a >> 2 = 3

7. Practical Examples of Bitwise Operators

Example 1: Checking Odd or Even

You can use the bitwise AND operator to check if a number is odd or even.

using System;

public class OddEvenCheck
{
    public static void Main()
    {
        int number = 7;

        if ((number & 1) == 1)
        {
            Console.WriteLine("The number is odd.");
        }
        else
        {
            Console.WriteLine("The number is even.");
        }
    }
}

Explanation:

  • The expression number & 1 checks the least significant bit. If it’s 1, the number is odd; otherwise, it’s even.

Output:

The number is odd.

Example 2: Swapping Two Numbers Using XOR

You can use the XOR operator to swap two numbers without a temporary variable.

using System;

public class SwapUsingXor
{
    public static void Main()
    {
        int x = 5;
        int y = 10;

        x = x ^ y;
        y = x ^ y;
        x = x ^ y;

        Console.WriteLine("After swapping: x = " + x + ", y = " + y);
    }
}

Explanation:

  • XOR swapping allows x and y to be swapped without a temporary variable by combining the XOR operations.

Output:

After swapping: x = 10, y = 5

Example 3: Setting and Clearing Specific Bits

You can use bitwise operators to set, clear, or toggle specific bits in a number.

using System;

public class BitManipulationExample
{
    public static void Main()
    {
        int num = 8;      // Binary: 1000
        int bitToSet = 1; // Second bit (Binary: 0010)

        int setResult = num | bitToSet;      // Set second bit
        int clearResult = num & ~bitToSet;   // Clear second bit

        Console.WriteLine("Set second bit: " + Convert.ToString(setResult, 2));
        Console.WriteLine("Clear second bit: " + Convert.ToString(clearResult, 2));
    }
}

Explanation:

  • Set bit: num | bitToSet uses OR to set the second bit.
  • Clear bit: num & ~bitToSet uses AND with the inverted bit mask to clear the second bit.

Output:

Set second bit: 1010
Clear second bit

: 1000

Summary

Bitwise operators in C# allow manipulation of individual bits within numbers. Here’s a recap:

  • AND (&): Returns 1 if both bits are 1.
  • OR (|): Returns 1 if at least one bit is 1.
  • XOR (^): Returns 1 if the bits differ.
  • NOT (~): Inverts each bit.
  • Left Shift (<<): Shifts bits to the left, padding with zeros.
  • Right Shift (>>): Shifts bits to the right, filling with the sign bit.

You may also like