相当于php“ fnum”的java的unpack函数,将十六进制转换为浮点数的IEEE 754

时间:2019-02-04 09:53:50

标签: java php ieee-754 pack

我在PHP中具有以下功能:

function hex2float($strHex) {
   $array = unpack("fnum", pack("H*", $strHex));
   return $array['num'];
}

如何用Java编写它?

1 个答案:

答案 0 :(得分:1)

我想以这种方式转换此函数:

private Float hex2float(String hexStr) {
    Float result = null;
    try {
        byte[] decodes = Hex.decodeHex(hexStr.toCharArray());
        result = getFloat(decodes, 0);
    } catch (DecoderException e) {
        // log error
    }
    return result;
}

private float getFloat(byte[] b, int index) {
    int l;
    l = b[index + 0];
    l &= 0xff;
    l |= ((long) b[index + 1] << 8);
    l &= 0xffff;
    l |= ((long) b[index + 2] << 16);
    l &= 0xffffff;
    l |= ((long) b[index + 3] << 24);
    return Float.intBitsToFloat(l);
}