why do these two different?

Go To Last Post
5 posts / 0 new
Author
Message
#1
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

This..

uint32_t DAC;
uint16_t dist,span,zero;
span = 1000;
zero = 50;
DAC = 255*(dist-zero)/(span-zero);

with this...

uint32_t DAC;
uint16_t dist,span,zero;
span = 1000;
zero = 50;
DAC = (dist-zero);
DAC *=255;
DAC /= (span-zero);

both of them gave different result, the last one is the correct one. Theoretically both of them have the same meaning but produce different code size and check sum. Sorry, i don't see the assembly output.
Any explanation? Please, simple one.
Thanks.

KISS - Keep It Simple Stupid!

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

your first calculation is only doing 16bit math, but storing the result in a 32bit variable. In the second case it is a mix between 16 and 32bit math. (integer promotion rules of C)

Writing code is like having sex.... make one little mistake, and you're supporting it for life.

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

should i change all the variable type to 32bit?

KISS - Keep It Simple Stupid!

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Not necessarily. You have to look at the valid input range for each of the variables, and make sure you don't overflow at any particular point in the calculation. If you do, then cast that operation to 32bit.

Writing code is like having sex.... make one little mistake, and you're supporting it for life.

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

like this:

	DAC = (uint32_t) 255*(dist-zero)/(span-zero); 

yup, this works great!
Thanks

KISS - Keep It Simple Stupid!