Fastest way to get sign in Java?

前端 未结 3 877
忘了有多久
忘了有多久 2021-01-01 10:39

I\'d like to get the sign of a float value as an int value of -1 or 1.

Avoiding conditionals is always a good idea in reducing computationa

3条回答
  •  佛祖请我去吃肉
    2021-01-01 11:23

    If you just want the IEEE 754 sign bit from the float value you can use:

    /**
     * Gets the sign bit of a floating point value
     */
    public static int signBit(float f) {
        return (Float.floatToIntBits(f)>>>31);
    }
    

    This is very fast and has the advantage of no branches. I think it is the fastest you can get on the JVM.

    But make sure it is what you want! Especially watch out for the special cases, e.g. NaN can technically have either a 0 or 1 sign bit.

提交回复
热议问题