Hello experts, to avoid a division, I use integer arithmetics. The unsigned int x which is in the range of 2000 is first multiplied by a number s which is 2048 plus/minus 1000 and then shifted by 11 digits which should replace a division by 2048.
unsigned int near x; unsigned int s x = ( (unsigned long) x * (unsigned long) s ) >> 11 ;
First, I am pretty sure any compiler written today will convert var / 2048 to a proper right shift of 11 bits so let the compiler do the work for you. Second, only one term in an expression need be a larger type to convert the entire expression to that type. E.g.
x = (unsigned int) (x * s) / 2048UL;
x = (unsigned int) (x * s) / 2048UL; Unfortunately the above won't work as the cast to unsigned int has higher precedence than the division. You need to use: x=(unsigned int)((x*s)/2048UL); I feel it is always better to use parentheses to make your intentions clearer even when not required.
x = (unsigned int) (x * s) / 2048UL; Unfortunately the above won't work as the cast to unsigned int has higher precedence than the division. You need to use: x=(unsigned int)((x*s)/2048UL); Arg! Thanks. My bad. I certainly meant what you wrote. I feel it is always better to use parentheses to make your intentions clearer even when not required. I don't. Extra parentheses can actually harm readability in some cases. My mistake would not have been helped by parentheses since I put them in the wrong spot to begin with. My rule is, if the operators are on different levels of the precedence graph, don't use parentheses, e.g. this should be obvious to all C programmers:
if (0 < a && a < 100) ...
if ((0 < a) && (a < 100))
Please let me amend my previous post. I do believe in using parentheses when required.
View all questions in Keil forum