Shift operators

Shift operators are another type of Binary operator. They take two integer operands and left shift or right shift the bits by the number specified.

The following table lists the available shift operators:

Expression Description
<< This is an example of a Binary operator that allows you to shift the first operand left by the number of bits specified in the second operand. The second operator must be a type of Int.
>> This is an example of a Binary operator that allows you to shift the first operand right by the number of bits specified in the second operand. The second operator must be a type of Int.

 

In the following example, the program accepts an integer operand and shifts left or right by 1 bit. Shift works on Binary operators, so, for our understanding, I wrote a method that will convert an integer into Binary format and display it. When we pass an integer number of 9 to the program, i, and use the >> operator, its Binary string is shifted by 1 and the result is displayed. When 1001 is right-shifted, it becomes 100:

public static string IntToBinaryString(int number)
{
const int mask = 1;
var binary = string.Empty;
while (number > 0)
{
// Logical AND the number and prepend it to the result string
binary = (number & mask) + binary;
number = number >> 1;
}
return binary;
}

// '>>' Operator
Console.WriteLine("'>>' operator");
int number = 9;
Console.WriteLine("Number is : {0} and binary form is {1}:", number, IntToBinaryString(number));
number = number >> 1;
Console.WriteLine("Number is : {0} and binary form is {1}:", number, IntToBinaryString(number));

//Output:
//Number is : 9 and binary form is 1001
//Number is : 4 and binary form is 100

// '<<' Operator
Console.WriteLine("'<<' operator");
Console.WriteLine("Number is : {0} and binary form is {1}:", number, IntToBinaryString(number));
number = number << 1;
Console.WriteLine("Number is : {0} and binary form is {1}:", number, IntToBinaryString(number));

//Output:
//Number is : 4 and binary form is 100
//Number is : 8 and binary form is 1000
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.20.90