Java Bitwise Operators right shift operator

Introduction

The right shift operator >> shifts all of the bits in a value to the right by num of times.

Its general form is shown here:

value >> num 

Here, num specifies the number of positions to right-shift the value.

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                                                                          

The bits that are shifted off are lost.

If you shift the value 35 to the right two positions, and the two low-order bits will be lost, the result would be 8:

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

Operation in binary form:

00100011   35 
>> 2 
00001000    8 
public class Main {
  public static void main(String args[]) {
    int a = 32;//from   ww w.  j a v a 2s  . c o  m
    
    System.out.println(a >> 2);
    
    a = 35;
    System.out.println(a >> 2);
  }
}

When shifting right, the left-most(top) bits are filled in with the previous contents of the top bit.

This is called signed right shift and can 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 

If you shift -1 right, the result always remains -1, since shift operation adds 1 in the high-order bits.

You can use mask to discard any sign bits.

The following code converts an int value to its hexadecimal string representation.

The shifted value is masked by using AND operation with 0x0f to discard any sign-extended bits.

// Masking sign extension.
public class Main {
  static public void main(String args[]) {
    char hex[] = {
      '0', '1', '2', '3', '4', '5', '6', '7',
      '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
    };/*from   w ww. ja v  a  2  s. c o  m*/
    int b = 0xf1;
    
    System.out.println(Integer.toBinaryString(b));
    System.out.println(b);
    System.out.println("b = 0x" + hex[(b >> 4) & 0x0f] + hex[b & 0x0f]);
  }
}



PreviousNext

Related