Use the shift operators to multiply and divide by 2

image_pdfimage_print

/*
C#: The Complete Reference
by Herbert Schildt

Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/
// Use the shift operators to multiply and divide by 2.
using System;

public class MultDiv {
public static void Main() {
int n;

n = 10;

Console.WriteLine(“Value of n: ” + n);

// multiply by 2
n = n << 1; Console.WriteLine("Value of n after n = n * 2: " + n); // multiply by 4 n = n << 2; Console.WriteLine("Value of n after n = n * 4: " + n); // divide by 2 n = n >> 1;
Console.WriteLine(“Value of n after n = n / 2: ” + n);

// divide by 4
n = n >> 2;
Console.WriteLine(“Value of n after n = n / 4: ” + n);
Console.WriteLine();

// reset n
n = 10;
Console.WriteLine(“Value of n: ” + n);

// multiply by 2, 30 times
n = n << 30; // data is lost Console.WriteLine("Value of n after left-shifting 30 places: " + n); } } [/csharp]