十六进制浮点转十进制浮点型

时间:2022-01-11 19:13:08
public static double modbusFloat(byte[] bits) {
        double rtn = 0;
        int flag = 1;
        if (bits.length == 4) {
            int E = bits[0] & 0x80;
            if (E > 0) {
                flag = -1;
            }

            E = ((bits[0] & 0x7F) << 1) + ((bits[1] & 0x80) >> 7);
            // 0x41360000 0 10000010 01101100000000000000000
            double M10 = 0.0;
            for (int i = 1; i <= 7; i++) {
                M10 += (bits[1] >> (7 - i) & 0x01) * Math.pow(2, -1 * i);
            }
            for (int i = 1; i <= 8; i++) {
                M10 += (bits[2] >> (8 - i) & 0x01) * Math.pow(2, -1 * (i + 7));
            }
            for (int i = 1; i <= 8; i++) {
                M10 += (bits[3] >> (8 - i) & 0x01) * Math.pow(2, -1 * (i + 15));
            }

            String data = "" + (1.0 + M10);
            double dVal = Double.parseDouble(data);
            rtn = flag * dVal * (Math.pow(2, E - 127));
        }
        // 00110011001100110100000000010011
        return rtn;
    }