Bit Shifting and Order of Operations

A quick refresher on the order of operations for those of you that have been out of the math game for a while.  The following two statements are true

1 + 4 / 2 = 3

(1 + 4) / 2 = 2.5

The reason is the mathematical concept of order of operations where by portions of an equation are evaluated before others.  The most basic and easily remember is multiplication and division (* and /) are evaluated before addition and subtraction (+ and -).  Portions of the equation within parens are evaluated before either.  You may remember Please Excuse My Dear Aunt Sally from grade school, but Sally doesn't have an excuse for bit shifting. 

The 'Shift' operator (<< and >>) shifts the bits in an int/long value to the left or the right, essentially multiplying or dividing the value by 2^n.  ex.

4 >> 1 = 2 = 4 / 2^1

4 << 2 = 16 = 4 * 2^2

1000 >> 3 = 125 = 1000 / 2^3

Why would you use the bit shift operator?  Bottom line, it is much faster than doing multiplication or division.  If you have ever read an intro to game programming book, those crazy-vector-math-genius-turned-programmers use the shift operator all the time.  I'm working on a rudimentary image viewer and thought I'd be cool and use it for centering images on the screen.

I started running into problems though and quickly determined the problem to be order of operations.  My presumption was that since the shift operator is essentially multiplication and division, it should have the same operator precedence.  But I was wrong.

1 + 4 >> 1 != 1 + 4 / 2

1 + 4 >> 1 = 5 >> 1 = 2

1 + (4 >> 1) = 3

Don't be a victim, paren your bit shift :)

posted @ Friday, January 19, 2007 2:13 PM


Print

Comments on this entry:

# re: Bit Shifting and Order of Operations

Left by name at 2/22/2007 1:38 AM
Gravatar

Also, / precedes *. So<br />6/2*2 = 6 and<br />3*8/4/0.5 = 12

Your comment:



 (will not be displayed)


 
 
 
Please add 4 and 6 and type the answer here:
 

Live Comment Preview:

 
«August»
SunMonTueWedThuFriSat
272829303112
3456789
10111213141516
17181920212223
24252627282930
31123456