我想将 float
值的符号作为 -1 或 1 的 int
值。
避免条件始终是降低计算成本的好主意。例如,我能想到的一种方法是使用快速 bit-shift
来获取符号:
float a = ...;
int sign = a >> 31; //0 for pos, 1 for neg
sign = ~sign; //1 for pos, 0 for neg
sign = sign << 1; //2 for pos, 0 for neg
sign -= 1; //-1 for pos, 1 for neg -- perfect.
或者更简洁:
int sign = (~(a >> 31) << 1) - 1;
- 这看起来是个好方法吗?
- 考虑到字节序问题(MSB 持有符号),这是否适用于所有平台?
最佳答案
您不简单使用的任何原因:
int sign = (int) Math.signum(a); //1 cast for floating-points, 2 for Integer types
此外,大多数 Number 实现都有一个 signum 方法,该方法采用该类型的原语并返回一个 int,因此您可以避免强制转换以获得额外的性能。
int sign1 = Integer.signum(12); //no casting
int sign2 = Long.signum(-24l); //no casting
它将返回 +1/0/-1,并且已经过优化以提供良好的性能。
作为引用,你可以看看the implementation in openJDK .相关位是:
public static float signum(float f) {
return (f == 0.0f || isNaN(f)) ? f : copySign(1.0f, f);
}
public static boolean isNaN(float f) {
return (f != f);
}
public static float copySign(float magnitude, float sign) {
return rawCopySign(magnitude, (isNaN(sign) ? 1.0f : sign));
}
public static float rawCopySign(float magnitude, float sign) {
return Float.intBitsToFloat((Float.floatToRawIntBits(sign)
& (FloatConsts.SIGN_BIT_MASK))
| (Float.floatToRawIntBits(magnitude)
& (FloatConsts.EXP_BIT_MASK
| FloatConsts.SIGNIF_BIT_MASK)));
}
static class FloatConsts {
public static final int SIGN_BIT_MASK = -2147483648;
public static final int EXP_BIT_MASK = 2139095040;
public static final int SIGNIF_BIT_MASK = 8388607;
}
关于java - 登录 Java 的最快方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13988805/