codescracker


java

Java Right Shift



« Previous Tutorial Next Tutorial »


The right shift operator, >>, shifts all of the bits in a value to the right a specified number of times. Here is the general form to use right shift operator in Java:

value >> num

Here, num specifies the number of positions to right-shift the value in value i.e., the >> moves all of the bits in the specified value to the right the number of bit position specified by num.

The following code fragment shifts the value 32 to the right by two positions, resulting in a being set to 8 :

int a = 32;
a = a >> 2;      // a now contains 8

When a value has bits that are "shifted off," those bits are lost. For example, the next code fragment shifts the value 35 to the right two positions, which causes the two low-order bits to be lost, resulting again in a being set to 8:

int a = 35;
a = a >> 2;     // now a contains 8

Looking at the same operation in binary shows more clearly how this happens :

00100011   35
>>2
00001000   8

Each time you shift a value to the right, it divides that value by two, and discards any remainder. In some cases, you can take advantage of this for the high-performance integer division by 2.

When you are shifting right, the top (leftmost) bits exposed by the right shift are filled in with previous contents of the top bit. This is called sign extension and serves to preserve the sign of negative numbers when you shift them right. For example, -8 >> 1 is -4, which, in binary, is :

11111000   -8
>>1
11111100   -4

It is interesting to note that if you shift -1 right, the result always remains -1, since sign extension keeps bringing in more ones in the high-order bits.

Sometimes it is not desirable to the sign-extend values when you are shifting them to the right. For example, the following program converts a byte value to its hexadecimal string representation. Notice that the shifted value is masked by ANDing it with 0x0f to discard any sign-extended bits so that the value can be used as an index into the array of hexadecimal characters.

Java Right Shift Operator Example

Here is an example program, helps you in understanding the concept of right shift operator in Java:

/* Java Program Example - Java Right Shift
 * Masking sign extension. */

public class JavaProgram
{   
    public static void main(String args[])
    {
        
        char hex[] = {
            '0', '1', '2', '3', '4', '5', '6', '7',
            '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
        };
        
        byte b = (byte) 0xf1;
        
        System.out.println("b = 0x" + hex[(b >> 4) & 0x0f] + hex[b & 0x0f]);
        
    }
}

When the above Java program is compile and executed, it will produce the following output:

java right shift

« Previous Tutorial Next Tutorial »



Tools
Calculator

Quick Links
Signup - Login - Give Online Test