Fast sign of integer in C

前端 未结 5 1109
轮回少年
轮回少年 2020-12-06 11:57

There is a sign function in C:

int sign(int x)
{
    if(x > 0) return 1;
    if(x < 0) return -1;
    return 0;
}

Unfortunately, comp

5条回答
  •  不知归路
    2020-12-06 12:16

    int sign(int x)
    {
        // assumes 32-bit int and 2s complement signed shifts work (implementation defined by C spec)
        return (x>>31) | ((unsigned)-x >> 31);
    }
    

    The first part (x>>32) gives you -1 for negative numbers and 0 for 0 or positive numbers. The second part gives you 1 if x > 0 or equal to INT_MIN, and 0 otherwise. Or gives you the right final answer.

    There's also the canonical return (x > 0) - (x < 0);, but unfortunately most compilers will use branches to generate code for that, even though there are no visible branches. You can try to manually turn it into branchless code as:

    int sign(int x)
    {
        // assumes 32-bit int/unsigned
        return ((unsigned)-x >> 31) - ((unsigned)x >> 31);
    }
    

    which is arguably better than the above as it doesn't depend on implementation defined behavior, but has a subtle bug in that it will return 0 for INT_MIN.

提交回复
热议问题