← Back to C# Course | Chapter 3: Operators | Lesson 4 of 6

Bitwise Operators

Bitwise operators work on the tiny on-off switches inside a number, like flipping single light switches in a long row. They are useful for packing settings together compactly.

In this page:

  1. Bitwise Operators
Syntax
csharp
int result = a & b;    // AND
int result = a | b;    // OR
int result = a ^ b;    // XOR
int result = ~a;       // NOT
int result = a << n;   // shift left
int result = a >> n;   // shift right

Bitwise Operators

Bitwise operators (&, |, ^, ~, <<, >>) operate directly on the binary representation of integers. & and | perform AND/OR on each bit, ^ is XOR, <</>> shift bits left or right.

They're common in flags, masks, and low-level performance code.

Note: x << 1 doubles an integer, and x >> 1 halves it (for non-negative numbers).

Example: Bitwise Operators

markup
using System;

class Program
{
    static void Main(string[] args)
    {
        int a = 6;  // 110
        int b = 3;  // 011

        Console.WriteLine(a & b);   // 010 = 2
        Console.WriteLine(a | b);   // 111 = 7
        Console.WriteLine(a ^ b);   // 101 = 5
        Console.WriteLine(a << 1);  // 1100 = 12
        Console.WriteLine(a >> 1);  // 011 = 3
    }
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Using & when you meant &&, and getting a bitwise result on numbers instead of a bool.
  2. Shifting by a number of bits larger than the type size, which wraps the shift count.
  3. Forgetting that ~ flips every bit, so ~5 is -6 for an int.
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.