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