They arn’t graphics related, and i’m sure they’ve been posted elsewhere, but here are a few I have lying around:
public static final int abs(int a) {
return (a ^ (a >> 31)) - (a >> 31);
}
public static final int min(int a, int b) {
final int signBits = (a - b) >> 31;
// if b > a, signBits==0xFFFFFFFF
// else, signBits==0x00000000
return (b & ~signBits) | (a & signBits);
}
public static final int max(int a, int b) {
final int signBits = (a - b) >> 31;
return (b & signBits) | (a & ~signBits);
}
/**
*
* Optimised method to cap a value in the range of 0 to max, Where max is a
* non-negative integer (aka >=0, or Z-*)
*
* @param value
* The value to be capped
* @param max
* the maximum value
* @return
*/
public static final int cap(int value, int max) {
return value & ~(value >> 31) & ~((max - value) >> 31) | (((max - value) >> 31) & max);
}
Note.
They’re unlikely to be the optimal solution (improvements welcome ofcourse!)
They also aren’t guaranteed to be any faster than their respective conventional approaches. =)