Stop using right and left bit shifts for multiply and divide

Apr 29th 2018

It is not the 1970's any more and compilers are smart, often smarter than us programmers. 

School teaches us a lot but often what we learn is the wrong things. For example in school the hard problems are worth more points. In real life I seen countless engineers make problems hard so that is worth their skills to solve the problem.  The classic example is optimization of code, for example... 

x= x>>1; //divide by 2

This one line is an example of premature optimization and possibly shooting yourself in the foot.  For example do you think it generates different code than:

x=x/2; //divide by 2

Some might say yes, some might say no, and both are correct as it depends.  To understand this lets consider the case below:

int32_t divideBy2(int32_t x)
{
	return x>>1; //fast divide by 2
}
void main(void)
{
	int32_t y=-4;  
	y=divideBy2(-4); 
}
<br>

Now in this code you think at the end of main y would be -2, and for most processors and compilers this would be correct, however it is not guaranteed.  Specifically the C standard indicates that bit shifts may sign extend or may not, and is processor dependent.  So the bit shift may not divide by 2  with signed integers. 

So back in the 70's doing the bit shift was a good idea as the compiler would usually translate to one processor instruction.  Where if you used the '/' divide operator it would do a long and complex division.  Well today'd compilers are much smarter and if the divide can be done with bit shift, it will use the bit shift.  So if you meant to do a divide then do a divide and stop using bit shifts for division.

Using right and left shifts for setting bit flags can still be done, but if you meant to do math, use the math operator as it will be more portable code, and your code will make more sense to the next guy.