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); } }