Fast contactless maximum for unsigned integers

I found the AGGREGATE Magic trick for quickly calculating maximum values. The only problem is that this is for integers, and yet I tried some things, I have no idea how to make a version for unsigned integers.

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

Any tips?

EDIT

Do not use this because, as others have claimed, it creates undefined behavior. For any modern architecture, can the compiler issue a conditional conditional move return (a > b) ? a : b from return (a > b) ? a : b return (a > b) ? a : b , which will be faster than the corresponding function.

+8
c ++ algorithm bit-manipulation c ++ 11
source share
1 answer

What does this code do? It takes the value a and the difference a - b . Of course, a - (a - b) b . And (a - b) >> 31 just creates a mask if if a - b negative.

This code is incorrect if you get overflow on subtraction. This, however, is the same story as for unsigned integers. Therefore, if you are happy with the fact that your code is incorrect for the entire range of values, you can simply ignore the unsignedness and use this:

 inline uint32_t umax(uint32_t a, uint32_t b) { return (uint32_t)max((int32_t)a, (int32_t)b); } 
+9
source share

All Articles