29 Oct 2009

Efficient abs() in C

There are multiple ways to compute an absolute value in C, including linking with the math library (bloat!). Although using an if statement and multiplying by -1 might seem easy…

x = could_be_pos_or_neg();
if (x < 0) x *= -1;

… the branch is quite inefficient (if you care about such things).

A far more efficient method is to leverage the use of bitwise operations to change the representation of the integer. This is only really useful if you are compiling with something other than GCC (as it treats abs() as a built-in function).

#define mask(x) (x >> (sizeof(int) * 8) - 1)
#define abs(x) ({ \
    int __r = (x + mask(x)) ^ mask(x); \
    __r; \
})

Which now makes the call very easy:

int r = abs(-12);