plasmacel plasmacel - 1 year ago 81
C++ Question

Fast branchless max for unsigned integers

I have a great trick from the AGGREGATE Magic for fast computing max values. The only problem that this is for integers, and however I have tried some things, have no idea how to make a version for unsigned integers.

inline int32_t max(int32_t a, int32_t b)
return a - ((a-b) & (a-b)>>31);

Any advice?


Do not use this, because as others stated it produces undefined behaviour.

Answer Source

What does this code do? It takes the value of a and the difference a-b. Of course, a-(a-b) is b. And (a-b)>>31 simply creates a mask of ones iff a-b is negative.

This code is incorrect, iff you get an overflow on the subtraction. That, however is the same story as for unsigned integers. So iff you are content with the fact, that your code is not correct for the entire value range, you can simply ignore unsignedness and use this:

inline uint32_t umax(uint32_t a, uint32_t b) {
    return (uint32_t)max((int32_t)a, (int32_t)b);