C Sharp/Shift 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] C# Shift Operators


This section will discuss both C# bit shifting operators (<< and >>).


Here is a chart that describes the C# shift operators:


C# Shift Operators

Operator Name Description
<< Left Shift Shifts bits to the left by specified number of bits
>> Right Shift Shifts bits to the right by specified number of bits


Example: Shift left

x = 4, y;
y = x << 3;


The code above will left shift the bit pattern of x. This is how you would do it.

4 = 1  0  0
1  0  0                //Bit pattern for 4
1  0  0  0  0  0       //Bits are shifted 3 times to the left

Notice: When bits are shifted 2 zeros are created



Example: C# Shift right

x = 5, y;
y = x >> 1;

The code above will right shift the bit pattern of x. This is how you would do it.

5 = 1  0  1

1  0  1        //Bit pattern for 5
0  1  0        //Shift to right 1 time. The last bit is lost.

Notice: When bits are shifted the trailing 1 falls off


Lets see this idea in some C# code:


using System;
class Test
{
    static void Main()
    {
        //33 = 1 0 0 0 0 1
        Console.WriteLine(33 >> 3);
 
        //15 = 1 1 1 1
        Console.WriteLine(15 << 2);
        Console.Read();
    }
}

OutPut:

4

60
Personal tools
Interesting Sites
ListSergeant