Page 35 - CTS - CSA TP - Volume 2
P. 35

COMPUTER SOFTWARE APPLICATION - CITS




           3  Examples:
              •  System.out.println(10 >> 2);
              •  Right shift the binary representation of 10 by 2 positions.
              •  10 in binary is 1010. After right shifting by 2, it becomes 10, which is 2 in decimal.
              •  Output: 2
              •  System.out.println(20 >> 2);
              •  Right shift the binary representation of 20 by 2 positions.
              •  After right shifting by 2, 20 becomes 5 in decimal.
              •  Output: 5
              •  System.out.println(20 >> 3);
              •  Right shift the binary representation of 20 by 3 positions.
              •  After right shifting by 3, 20 becomes 2 in decimal.
              •  Output: 2
           Output:




















           TASK 8: Java Shift Operator Example: >>vs>>>
           public class OperatorExample8{
           public static void main(String args[]){

               //For positive number, >> and >>> works same
               System.out.println(20>>2);
               System.out.println(20>>>2);
               //For negative number, >>> changes parity bit (MSB) to 0

               System.out.println(-20>>2);
               System.out.println(-20>>>2);
           }}
           Explanation:
           1  Right Shift Operator (>>):

              •  The right shift operator (>>) shifts the bits of a binary number to the right by a specified number of positions.
              •  For positive numbers, the vacant leftmost positions are filled with the sign bit (MSB, Most Significant Bit).
           2  Unsigned Right Shift Operator (>>>):
              •  The unsigned right shift operator (>>>) also shifts the bits to the right, but it fills the vacant leftmost positions
                 with zeros, irrespective of the sign bit.
              •  It treats the number as if it were an unsigned quantity.




                                                           20
                                CITS : IT & ITES - Computer Software Application - Exercise 82
   30   31   32   33   34   35   36   37   38   39   40