求绝对值的方法汇总


void fnTestAbs()
{
    /** abs库函数的调试版
    int __cdecl abs (
    int number
    )
    {
    return( number>=0 ? number : -number );
    }
    */

    int iA = -789;
    int iB = 789;

    float fA = -789;
    float fB = 789;

    /// 调用库函数实现
    fA = fabsf(fA); ///< M$真抠门, 到 fabs 已经没有源码实现了
    fB = fabsf(fB);

    iA = abs(iA);
    iB = abs(iB);

    /// 用短路表达式, 实现形式上的无分支
    iA = -789;
    iB = 789;
    iA = absEx1(iA);
    iB = absEx1(iB);

    /// 1. 真正的无分支方法实现abs
    iA = -789;
    iB = 789;
    iA = absEx2(iA);
    iB = absEx2(iB);

    /// 2. 真正的无分支方法实现abs
    iA = -789;
    iB = 789;
    iA = absEx3(iA);
    iB = absEx3(iB);
}

int absEx1(int iIn)
{
    (iIn < 0) && (iIn = -iIn);
    return iIn;
}

int absEx2(int iIn)
{
    /// 得到符号位为原始符号代表的值 * 原值
    /// 如果符号位为-, 得到-1(0xFFFFFFFF) | 1 = -1
    /// 如果符号位为+, 得到0(0x00000000) | 1 = 1
    return ((iIn >> 31) | 1) * iIn;
}

int absEx3(int iIn)
{
    int m = iIn >> 31;
    /// 得到符号位组成的int值
    /// if (iIn > 0), m = 0;
    /// if (iIn < 0), m =  0xffffffff;

    iIn = iIn ^ m; ///< 取反
    /// if (iIn > 0), iIn = iIn ^ 0 = iIn; 不变
    /// if (iIn < 0), iIn = iIn ^ 0xffffffff = ~iIn;

    iIn = iIn - m; ///< 加1
    /// if (iIn > 0), iIn = iIn - 0 = iIn;
    /// if (iIn < 0), iIn = iIn - 0xffffffff = iIn - (-1) = iIn + 1;
    /// 负数取反+1, 变成了正数

    return iIn;
}


展开阅读全文

没有更多推荐了,返回首页