tips.shift
Class ShiftExample

java.lang.Object
  extended bytips.shift.ShiftExample

public class ShiftExample
extends java.lang.Object

ShiftExample is a sample class demonstrating the use of the Java >> >>> and << operators and demonstrating the difference between >> and >>>.

Usage: java ShiftExample Number ShiftBy

  1. Number - a number that you want to shift
  2. ShiftBy - the number of bits you want to shift the number

when using this program try both positive and negative numbers.

Reduction of the right operand

Note that if you use a shift number that is greater than the length of the variable type (ie for int this would be a number greater than 32) then the Java compiler will take the modulus of that number. For example: 2 >> 33 would become 2 >> (33 % 32) or 2 >> 1

Promotion of Operands

When shifting number smaller than an int the results can be unexpected. for example consider
byte b = -64;
byte c = b >>> 4;

The original number will be: 11000000
Promoting to an int gives: 11111111111111111111111111000000
Shift right unsigned 4 gives: 0000111111111111111111111111111111111100
Truncate to byte gives: 11111100
The expected result may have been: 00001100

Since:
J2SE 1.4

Constructor Summary
ShiftExample()
          Creates a new instance of ShiftExample
 
Method Summary
(package private)  void display(int num, int shift)
          Go through a display the number in binary form, with an without the shift operators applied
private  java.lang.String format(int num)
          Format a number in binary form.
static void main(java.lang.String[] args)
           
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

ShiftExample

public ShiftExample()
Creates a new instance of ShiftExample

Method Detail

main

public static void main(java.lang.String[] args)
Parameters:
args - the command line arguments

display

void display(int num,
             int shift)
Go through a display the number in binary form, with an without the shift operators applied


format

private java.lang.String format(int num)
Format a number in binary form.

Note that your could use Integer.toBinaryString() but that will lose MSBs if ZERO.