C Sharp/Bitwise Operators

From Meshplex

Jump to: navigation, search
Image:Csharp_programming.gif

Main Home

Basics
C# Tutorial Home
C# - Introduction to Visual Studio IDE
Introduction to C#
C# - Overview
C# - Statements
C# - Data Types
C# - Variables
C# - Operators

C# - Flow Control
C# - Variables II
C# - Functions and Methods
C# - Classes and Objects I
C# - Enumerations
C# - Dates and Times
C# - Random Numbers

Advanced
C# - Inheritance
C# - Polymorphism
C# - Garbage Collection
C# - Operator Overloading
C# - Encapsulation
C# - Properties
C# - Indexers
C# - Exceptions
C# - GUI
C# - Delegates
C# - Events
C# - Components
C# - Multithreading
C# - Regular Expressions
C# - Graphics and Multimedia
C# - Files and Streams
C# - XML
C# - Database, SQL and ADO.NET
C# - ASP.NET Web Forms and Web Controls
C# - Web Services
C# - Network Programming
C# - Datastructures and Collections
C# - Enumerations and Iterators
C# - .NET Assemblies
C# - CLR
C# - Visual Studio Debugger
C# - Namespaces
C# - Generics
C# - MS Intermediate Language
C# - Deploying Windows Application

[edit] The & (AND) Operator


This section will teach you the basics of the C# & and | operators.



If we want to & the numbers 5 and 4 we simply compare each bit in the first number with each bit in the second number. Here is a chart for &

Note: When you compare each bit make sure they share the same position.



& Bit Comparison Chart

First Number Second Number Result   &
1 1 1
1 0 0
0 1 0
0 0 0


Now lets compare two numbers. We will compare numbers 4 and 5. Refer to the chart above to compare the bits.


5 = 1  0  1
4 = 1  0  0
------------
    1  0  0


Starting from the left:

  • Position 1: 1
  • Position 2: 0
  • Position 3: 0


The answer:

1   0   0   =   4


Code:

using System;
class Test
{
    static void Main()
    {
 
        int a = 5;
        int b = 4;
 
        Console.WriteLine(a & b);
        Console.Read();
    }
}

Output:

4

[edit] The | (OR) Operator

Here is the chart for the | operator:


| Bit Comparison Chart

First Number Second Number Result     |
1 1 1
1 0 1
0 1 1
0 0 0


Now lets compare two numbers. We will compare numbers 4 and 5. Refer to the chart above to compare the bits.


5 = 1  0  1
4 = 1  0  0
------------
    1  0  1


Starting from the left:

  • Position 1: 1
  • Position 2: 0
  • Position 3: 1


The answer:

1   0   1   =   5


Code:

using System;
class Test
{
    static void Main()
    {
 
        int a = 5;
        int b = 4;
 
        Console.WriteLine(a | b);
        Console.Read();
    }
}

Output:

5