Use the shift operators to multiply and divide by 2 : Bitwise Shift « Data Type « C# / CSharp Tutorial






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); 
 
  } 
}
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








2.46.Bitwise Shift
2.46.1.The shift << operators
2.46.2.>> operators
2.46.3.Use the shift operators to multiply and divide by 2
2.46.4.left shift
2.46.5.right shift