Difference between revisions of "Embedded Programming Tips and Tricks"

From EEVblog Electronics Resource Wiki
Jump to: navigation, search
(Fast Division)
(Fast Division)
Line 1: Line 1:
 
===Fast Division===
 
===Fast Division===
On microcontrollers without a divide instruction very fast division can be done by bit shifting a variable right.
+
On microcontrollers without a divide instruction very fast division can be done by bit shifting a variable right.<br>
Each shift does a divide by two.
+
Each shift does a divide by two.<br>
  
For example
+
For example<br>
Y = Y >> 1  Will result in a divide by 2
+
Y = Y >> 1  Will result in a divide by 2<br>
or
+
or<br>
X = X >> 4  Will result in a divide by 16
+
X = X >> 4  Will result in a divide by 16<br>
  
By adding a multiplication you can achieve other, more complex, divisions.
+
By adding a multiplication you can achieve other, more complex, divisions.<br>
  
For example
+
For example<br>
Z = Z * 3;
+
Z = Z * 3;<br>
Z = Z >> 4;  (div 16)
+
Z = Z >> 4;  (div 16)<br>
  
Will result in a division of 5.33 (16/3 = 5.33)
+
Will result in a division of 5.33 (16/3 = 5.33)<br>
  
Be sure to do the multiply first, otherwise bits will be lost.
+
Be sure to do the multiply first, otherwise bits will be lost.<br>
Also be sure the variable size is large enough to store the multiplied value.
+
Also be sure the variable size is large enough to store the multiplied value.<br>

Revision as of 22:36, 12 November 2011

Fast Division

On microcontrollers without a divide instruction very fast division can be done by bit shifting a variable right.
Each shift does a divide by two.

For example
Y = Y >> 1 Will result in a divide by 2
or
X = X >> 4 Will result in a divide by 16

By adding a multiplication you can achieve other, more complex, divisions.

For example
Z = Z * 3;
Z = Z >> 4; (div 16)

Will result in a division of 5.33 (16/3 = 5.33)

Be sure to do the multiply first, otherwise bits will be lost.
Also be sure the variable size is large enough to store the multiplied value.