Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

1) The right shift in java is an arithmetic shift while in C\C++ is implementation defined (logical or arithmetic)
2) In C\C++ if the value being left shifted is negative or the right hand operator of the shift operation is negative or greater than or equal to the width of the promoted left operand we have umdefined behaviour. This does not apply in Java since for the case of integer type it is masked with 0x1F and as a result we can always have a value that is modulo 31. When the value to be shifted (left-operand) is a long, only the last 6 bits of the right-hand operand are used to perform the shift. The actual size of the shift is the value of the right-hand operand masked by 63 (0x3D) Java Language Specification(§15.19 )
ie the shift distance is always between 0 and 63 (if the shift value is greater than 64 shift then the shift is 64%valuevalue%64)

                  35             00000000 00000000 00000000 00100011

...

Although we can not have undefined behaviour in Java we still have to ensure that we get the correct results. So we should
explicitly check for ranges

Code Block
bgColor#ccccff
public int do_shift(int shift_value){ 
   if(shift_value > 31 or shift_value <0)if(shift_value > 31 or shift_value <0)
      throw ArithmeticException;
   else
int val = 2 << shift_value;
  throw ArithmeticException;
else
int val = 2 << shift_value;
}








Unsigned Right shifting >>>

...