# Tips and Tricks – Fast Divide and Multiply

There are many instances when attempting to perform a mathematical operation on a resource-constrained microcontroller where the use of a simple divide or multiply can drastically affect the speed and efficiency of the system. There is often little that can be done to get around the division or multiplication but there is a neat trick that can be performed to make these operations extremely fast. Consider how information is stored inside of a computer system. Every object in the system consists of bits that are encoded in 2 to the power of n. For example, the value of 2 raised to 2 is 2*2 = 4. The value of 2 raised to 4 is 2*2*2*2* = 16. What is so interesting about how numbers are stored is that shifting the value of an object to the left behaves like a multiplication and a shift to the right acts like a divide.

Keeping this behavior in mind, algorithms can be developed to take advantage of the bit shift behavior. For example, a commonly performed task in an embedded system is to average values that are being read by an analog-to-digital converter. A developer can keep the 2 to n behavior of values in mind to average the last four adc reads. The pseudo code would look like