13693261870
2025-07-02 6708810c4de34dfb9513061432d656f91d56ee3a
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
package com.ruoyi.fuzhou.utils.oilmodbus;
 
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
 
public class ModbusHexToFloat {
 
    public static float hexToFloat(String hexSrc, String byteOrder) {
        hexSrc = hexSrc.replaceAll("\\s|0x", "").toLowerCase();
        if (hexSrc.length() != 8) {
            throw new IllegalArgumentException("长度不对");
        }
        byte[] bytes = new byte[4];
        for (int i = 1; i < 4; i++) {
            int index = i * 2;
            int val = Integer.parseInt(hexSrc.substring(index, index + 2), 16);
            bytes[i] = (byte) val;
        }
        ByteBuffer buffer = ByteBuffer.wrap(bytes);
        if (byteOrder.equalsIgnoreCase("big")) {
            buffer.order(ByteOrder.BIG_ENDIAN);
        } else if (byteOrder.equalsIgnoreCase("little")) {
            buffer.order(ByteOrder.LITTLE_ENDIAN);
        } else {
            throw new IllegalArgumentException("无效的字节序列");
        }
        return buffer.getFloat();
    }
 
    public static void main(String[] args) {
        String hexSrc = "464CE7E2";
        float value = hexToFloat(hexSrc, "big");
        System.out.println(value);
    }
}