The term “wealthy” is perfectly suited for the upcoming discussion on C language. They dominate the embedded C language with luxury, but we ultimately need a more economical micro-ecosystem. Here, I will briefly analyze the use of division and shifting in embedded C language programming.
Division Wealthy
Division can be considered a major consumer in embedded microprocessors; its complex implementation not only consumes precious computation time but also occupies a large amount of RAM under limited precision. Therefore, it is often seen in various articles that programmers should use right shift operations to replace division. This right shift method is valid and indeed can enhance the computational capability of microprocessors, saving processing time. However, we must note that this method is only applicable to integer operations for division by powers of 2, such as 2, 4, 8, 16, etc. I do not agree with the statement “try to use right shift instead of division”. This is mainly because the current programming environments can optimize such operations; for division by powers of 2, if the compiler deems that shifting is better than division, it will automatically compile it into a shifting operation without user intervention.
Let’s assume another scenario: we are processing a data collection where each group contains 16 data points, and we sum these 16 data points iteratively, then right shift by 4 bits (divide by 16). However, this could pose a significant hidden risk for future updates to our program. Suppose the number of iterations for summation is defined by a #define directive, and for a particular collection, we only need 15 data points instead of 16; we update it to 15. In this case, we would have to redesign and rewrite our program—replacing all the tedious shifts with division. Of course, if we are not aware that the divisor for averaging is a right shift of 4 bits, then the 15 data points will still be divided by 16 for averaging, and the result is predictable.
Use shifting when shifting is needed, and division when it is division
Various bugs in software originate from the original authors, but more often they arise from updates, maintenance, and porting of the program. Therefore, software code should have strong readability and good portability. Unless dealing with special functions and structures, most optimizations should be left to the compiler!