CSC231 Difference between shifting and dividing

From dftwiki3
Jump to: navigation, search

--D. Thiebaut 16:15, 23 October 2012 (EDT)


  • Be careful when you shift negative numbers to perform divisions by a power of two. The result is not quite the same as dividing by the power of 2.
  • This is true in assembly and other languages, such as Java:

Example


// ShiftRight.java
// D. Thiebaut
// To compile and run:
//       javac ShiftRight.java
//       java ShiftRight

public class ShiftRight {

    public static void main(String[] args) {
	for ( int i=-10; i<10; i++ ) {
	    int a = i >> 1;
	    int b = i / 2;
	    System.out.println( "i = " + i + " i >> 1  = " + a + " i / 2  = " + b );
	}
    }
}


Output


i = -10 	i >> 1  = -5 	i / 2  = -5
i = -9 	i >> 1  = -5 	i / 2  = -4
i = -8 	i >> 1  = -4 	i / 2  = -4
i = -7 	i >> 1  = -4 	i / 2  = -3
i = -6 	i >> 1  = -3 	i / 2  = -3
i = -5 	i >> 1  = -3 	i / 2  = -2
i = -4 	i >> 1  = -2 	i / 2  = -2
i = -3 	i >> 1  = -2 	i / 2  = -1
i = -2 	i >> 1  = -1 	i / 2  = -1
i = -1 	i >> 1  = -1 	i / 2  = 0
i = 0 	i >> 1  = 0 	i / 2  = 0
i = 1 	i >> 1  = 0 	i / 2  = 0
i = 2 	i >> 1  = 1 	i / 2  = 1
i = 3 	i >> 1  = 1 	i / 2  = 1
i = 4 	i >> 1  = 2 	i / 2  = 2
i = 5 	i >> 1  = 2 	i / 2  = 2
i = 6 	i >> 1  = 3 	i / 2  = 3
i = 7 	i >> 1  = 3 	i / 2  = 3
i = 8 	i >> 1  = 4 	i / 2  = 4
i = 9 	i >> 1  = 4 	i / 2  = 4