// file Shift.java
// examine the operation of the java shift operators
// <<  left shift : discard high order bits, 0's shifted into low order bits
// >>  right shift sign extend: sign extend in high bits, low order discarded
// >>> right shift unsigned : 0's shifted into high  bits,low order discarded
// 
// Shift left one place multiplies  by 2 
// Shift right sign extend one place divides by two (most of the time)
// These operations can only be used with integer primitives
// 
public class Shift { 
	public static void main(String args[]) { 
		int a = 0xFFFFFF40, b = 0x000000C0, c, d, e, f; 
		System.out.println("a is: "+ a +" b is: "+b);
		
		// SHIFT RIGHT SIGN EXTEND
		// shift right sign extend, sign is extended, low order bits discarded
		// -192 four places result is : 
		// 1111 1111 1111 1111 1111 1111 1111 0100
		c = a >> 4; 
		System.out.println("c is: "+c);
		System.out.println("Bit pattern 0xFFFFFFF4 equals: "+0xFFFFFFF4);
		// NOTE : -192/2 = -96
		//         -96/2 = -48
		//         -48/2 = -24
		//         -24/2 = -12
		// Shift right, sign extend is an efficient way to 
		// divide by 2
		
		// SHIFT RIGHT UNSIGNED
		// shift right unsigned 0's shited in, low order bits discarded
		// -192 right unsigned, four places,  result is: 
		// 0000 1111 1111 1111 1111 1111 1111 0100
		d = a >>>4; 
		System.out.println("d is :"+d); 
		System.out.println("Bit pattern 0x0FFFFFF4 equals: "+0x0FFFFFF4);
		
		// SHIFT LEFT
		// shift left , 0's shifted in, high order bits discarded
		// -192 left four places , result is: 
		// 1111 1111 1111 1111 1111 0100 0000 0000
		e = a <<4; 
		System.out.println("e is :"+e); 
		System.out.println("Bit pattern 0xFFFFF400 equals: "+0xFFFFF400);
		// NOTE: 
		//  -192 * 2 =   -384
		//  -384 * 2 =   -768
		//  -768 * 2 =   -1536
		// -1536 * 2 =   -3072
		// Shift left is an efficient way to multiply by 2
		
		// RIGHT HAND REDUCTION
		// What happens when I trt to shift a 32 bit int, more than 32 
		// places ? 
		// The right hand operand is reduced modulo 32. If I attempt
		// to shift 33 places the right hand is reduced to 33 % 32
		// resulting in a shift of 1 !!!
		f = a <<33; 
		System.out.println("f is :"+f); 
		
		//AUTOMATIC PROMOTION OF OPERANDS
		// When applying binary operators, all operands are promoted 
		// to at least int. Consider the consequences when attempting 
		// to do an unsigned right shift on bytes and shorts
		byte b1 = -32; 
		int b2; 
		b2 = (b1 >>>1); 
		System.out.println("b2 is :"+b2); 
	}
}