Use the shift operators to multiply and divide by 2
using System;
class Example {
public static void Main() {
int n;
n = 10;
Console.WriteLine("Value of n: " + n);
Console.WriteLine("multiply by 2");
n = n << 1;
Console.WriteLine("Value of n after n = n * 2: " + n);
Console.WriteLine("multiply by 4");
n = n << 2;
Console.WriteLine("Value of n after n = n * 4: " + n);
Console.WriteLine("divide by 2");
n = n >> 1;
Console.WriteLine("Value of n after n = n / 2: " + n);
Console.WriteLine("divide by 4");
n = n >> 2;
Console.WriteLine("Value of n after n = n / 4: " + n);
Console.WriteLine();
Console.WriteLine("reset n");
n = 10;
Console.WriteLine("Value of n: " + n);
Console.WriteLine("multiply by 2, 30 times");
n = n << 30; // data is lost
Console.WriteLine("Value of n after left-shifting 30 places: " + n);
}
}
Output
Value of n: 10
multiply by 2
Value of n after n = n * 2: 20
multiply by 4
Value of n after n = n * 4: 80
divide by 2
Value of n after n = n / 2: 40
divide by 4
Value of n after n = n / 4: 10
reset n
Value of n: 10
multiply by 2, 30 times
Value of n after left-shifting 30 places: -2147483648