absolute value of a subtraction

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

Hello,

I have two unsigned values and want to get the absolute value of their difference. Is it correct with the following code?

UINT16 value1, value2, abs_diff;
abs_diff = abs(value1 – value2);

Thank you
Senmeis

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

abs() uses type `int' as argument. unsigned -> int conversion might
cause funny results. I'd use a macro like:

#define ABSDIFF(a, b) ((a) < (b)? ((b) - (a)): ((a) - (b)))

Note that this macro evaluates its arguments more than once, so be
careful about any side effects (like pre/post-increment/decrement
operators).

Jörg Wunsch

Please don't send me PMs, use email if you want to approach me personally.