获得标志在Java中最快的方法? [英] Fastest way to get sign in Java?

查看:138
本文介绍了获得标志在Java中最快的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想获得一个浮动的迹象值为-1或1 INT 价值

避免条件句是始终在降低计算成本是一个好主意。举例来说,我能想到的一个方法是使用一个快速位移来得到符号:

 浮动= ...;
INT符号= A>> 31; // 0 POS机,1负
符号=〜标志; // 1 POS,0为负
签署等号(=)<< 1; // 2 POS,0为负
签 - = 1; // - 1 POS,1负 - 完美。

或者更简洁:

  INT签署=(〜(A>> 31);< 1) -  1;


  1. 这是否看起来是一个好办法?

  2. 将这项工作在所有平台上,字节顺序给予关注(如MSB持有符号)?


解决方案

你为什么不直接将任何方面的原因:

  INT签署=(int)的Math.signum(一);

这将返回+1 / 0 / -1,并进行了优化,提供了良好的业绩。

有关的参考,可以看看<一个href=\"http://hg.openjdk.java.net/jdk7/tl/jdk/file/84792500750c/src/share/classes/sun/misc/FpUtils.java\">the实施OpenJDK的。相关的位是:

 公共静态浮动正负号(浮动六){
    返程(F = = || 0.0 isNaN(F))? F:复制符号(1.0F,F);
}公共静态布尔isNaN(浮点六){
    返回(F = F!);
}公共静态浮动复制符号(浮动幅度,浮动符号){
    返回rawCopySign(大小,(isNaN(符号)1.0F:征));
}公共静态浮动rawCopySign(浮动幅度,浮动符号){
    返回Float.intBitsToFloat((Float.floatToRawIntBits(符号)
            &安培; (FloatConsts.SIGN_BIT_MASK))
            | (Float.floatToRawIntBits(幅度)
            &安培; (FloatConsts.EXP_BIT_MASK
            | FloatConsts.SIGNIF_BIT_MASK)));
}静态类FloatConsts {
    公共静态最终诠释SIGN_BIT_MASK = -2147483648;
    公共静态最终诠释EXP_BIT_MASK = 2139095040;
    公共静态最终诠释SIGNIF_BIT_MASK = 8388607;
}

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 computational cost. For instance, one way I can think of would be to use a fast bit-shift to get the sign:

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.

Or more concisely:

int sign = (~(a >> 31) << 1) - 1;

  1. Does this seem like a good approach?
  2. Will this work for all platforms, given endianness concerns (as MSB holds sign)?

解决方案

Any reasons why you don't simply use:

int sign = (int) Math.signum(a);

It will return +1 / 0 / -1 and it has been optimized to deliver a good performance.

For reference, you can have a look at the implementation in openJDK. The relevant bits are:

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中最快的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆