Noob int question

Go To Last Post
3 posts / 0 new
Author
Message
#1
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0
TCC1.CCA = (x * y) / 100;

In the operation above, x and y are unsigned ints. While in my application the result will always fit into an unsigned int, there are cases where (x * y) > two bytes. In these cases, CCA (which is two bytes) gets loaded with the wrong value. When doing int arithmetic, do all intermediate results have to fit in an int? If so, what's the fix? Parentheses, a cast, ...? Is there another explanation for my CCA problem? Thanks.

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

cast x and y to an uint32_t.

TCC1.CCA = ((uint32_t)x * (uint32_t)y)/100;
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

That did it. Thanks.