Shift Operators with int data type source code
package operators;
public class IntShiftOperators {
/**
* @param args
*/
public static void main(String[] args) {
int i=3;
//left shift operator
System.out.println(" i << 1 =" + (i <<1));
System.out.println(" i << 3 =" + (i <<3));
System.out.println(" i << 32 =" + (i <<32));//same as i
System.out.println(" i << 33 =" + (i <<33)); //same as <<1
i=44;
//right shift operator
System.out.println(" i << 1 =" + (i >>1));
System.out.println(" i >> 32 =" + (i >>32)); //same as i
i=255;
System.out.println(" i >> 7 (i is 0xff) =" + (i >>7));
System.out.println(" i >> 8 (i is 0xff) =" + (i >>8));
// unsigned right shift
System.out.println(" i >>> 7 (i is 0xff) =" + (i >>>7));
System.out.println(" i >>> 8 (i is 0xff) =" + (i >>>8));
System.out.println(" i >>> 32 =" + (i >>32)); //same as i
// all the above four yeilds the same result why ?
i = -222 ;
System.out.println(" i >> 1 =" + (i >>1));
System.out.println(" i >> 3 =" + (i >>3));
System.out.println(" i >>> 1 =" + (i >>>1));
System.out.println(" i >>> 3 =" + (i >>>3));
System.out.println(" i >>> 32 =" + (i >>>32));//same as i
}
}
output:
i << 1 =6
i << 3 =24
i << 32 =3
i << 33 =6
i << 1 =22
i >> 32 =44
i >> 7 (i is 0xff) =1
i >> 8 (i is 0xff) =0
i >>> 7 (i is 0xff) =1
i >>> 8 (i is 0xff) =0
i >>> 32 =255
i >> 1 =-111
i >> 3 =-28
i >>> 1 =2147483537
i >>> 3 =536870884
i >>> 32 =-222
0 comments:
Post a Comment