In my program, I have a statement like the following, inside a loop.
y = (x >= 1)? 0:1;
However, I want to avoid using any relational operator, because I want to use SIMD instructions, and am not sure if relational operators work well with SIMD.
I want something like the following.
a = some_operation(x) // a will be either 1 or 0
y = 1 - a
Where some_operation
would convert any number equal or greater than 1 to 1, and keep 0 to 0. So, my question is, is there any some_operation
that would achieve my purpose?
#define INT_BITS (CHAR_BIT * sizeof(int))
int make_zero_or_one(int x) {
return 1 - (((x-1) >> (INT_BITS-1)) & 1);
}
Like the other answers, this relies upon the MSB being the sign bit in ints. The function returns 0 for all ints <= 0 and 1 otherwise. The function will fail if x-1
overflows.
This implementation has no branches in compiled code.