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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package com.ruoyi.fuzhou.utils.oilmodbus;
 
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
 
/**
 * 16位浮点型数据转化搭数优先
 */
public class ModbusFloatParserUtil {
 
    public static void main(String[] args) {
        //String hexString = "BFC00000"; // 示例输入,-1.5
        String hexString = "464CE7E2"; // 示例输入,0.1234567
       // String hexString = "FF00"; // 示例输入,-1.5
        // 将十六进制字符串转换为字节数组
        byte[] bytes = hexStringToByteArray(hexString);
        // 解析为浮点数(大端字节顺序)
        float floatValue = parseAsFloat(bytes, ByteOrder.BIG_ENDIAN);
        // 输出结果
        System.out.println("解析的浮点数值: " + floatValue);
    }
 
    /**
     * 将十六进制字符串转换为字节数组
     */
    public static byte[] hexStringToByteArray(String s) {
        int len = s.length();
        if (len % 2 != 0) {
            throw new IllegalArgumentException("十六进制字符串长度必须为偶数。");
        }
        byte[] data = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            int high = Character.digit(s.charAt(i), 16) << 4;
            int low = Character.digit(s.charAt(i + 1), 16);
            if (high == -1 || low == -1) {
                throw new IllegalArgumentException("包含无效的十六进制字符: " + s);
            }
            data[i / 2] = (byte) (high + low);
        }
        return data;
    }
 
    /**
     * 将字节数组解析为浮点数
     * @param bytes 字节数组(必须为4字节)
     * @param order 字节顺序(大端或小端)
     */
    public static float parseAsFloat(byte[] bytes, ByteOrder order) {
        if (bytes.length != 4) {
            throw new IllegalArgumentException("字节数组长度必须为4字节。");
        }
        ByteBuffer buffer = ByteBuffer.wrap(bytes).order(order);
        return buffer.getFloat();
    }
}