Demonstrate the shift operators
/*
C#: The Complete Reference
by Herbert Schildt
Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/
// Demonstrate the shift << and >> operators.
using System;
public class ShiftDemo {
public static void Main() {
int val = 1;
int t;
int i;
for(i = 0; i < 8; i++) {
for(t=128; t > 0; t = t/2) {
if((val & t) != 0) Console.Write("1 ");
if((val & t) == 0) Console.Write("0 ");
}
Console.WriteLine();
val = val << 1; // left shift
}
Console.WriteLine();
val = 128;
for(i = 0; i < 8; i++) {
for(t=128; t > 0; t = t/2) {
if((val & t) != 0) Console.Write("1 ");
if((val & t) == 0) Console.Write("0 ");
}
Console.WriteLine();
val = val >> 1; // right shift
}
}
}
Related examples in the same category