What is different about C++ math.h abs() compared to my abs()

后端 未结 8 674
伪装坚强ぢ
伪装坚强ぢ 2021-02-07 07:44

I am currently writing some glsl like vector math classes in C++, and I just implemented an abs() function like this:

template
static         


        
8条回答
  •  我在风中等你
    2021-02-07 08:23

    There are well-known tricks for computing the absolute value of a two's complement signed number. If the number is negative, flip all the bits and add 1, that is, xor with -1 and subtract -1. If it is positive, do nothing, that is, xor with 0 and subtract 0.

    int my_abs(int x)
    {
        int s = x >> 31;
        return (x ^ s) - s;
    }
    

提交回复
热议问题