public class ModbusUtil { public static void main(String[] args) { System.out.println(floatIEE754Tohex(3.246434f)); System.out.println(doubleIEE754Tohex(-3.246434d)); System.out.println(hexIEE754ToFloat("404FC593", false)); System.out.println(hexIEE754ToDouble("c009f8b26394face", false)); } /**32位浮点数转16进制*/ public static String floatIEE754Tohex(Float d) { return Integer.toHexString(Float.floatToIntBits(d)); } /**64位浮点数转16进制*/ public static String doubleIEE754Tohex(Double d) { return Long.toHexString(Double.doubleToLongBits(d)); } /** * 16进制转换浮点数,IEE754浮点数占8个字节,两个寄存器地址 * 32位浮点数 * * @param interchange 是否高低位互换 */ public static Float hexIEE754ToFloat(String hex, boolean interchange) { if (hex.length() == 8) { String high = hex.substring(0, 4); String low = hex.substring(4, 8); if (interchange) { hex = low + high;//高低位互换 } int ieee754Int = Integer.parseUnsignedInt(hex, 16); float realValue = Float.intBitsToFloat(ieee754Int); return realValue; } else { throw new RuntimeException("待解析字符串必须是8位16进制字符"); } } /** * 16进制转换64位浮点数,IEE754浮点数占16个字节,四个寄存器地址 * 64位浮点数 */ public static Double hexIEE754ToDouble(String hex, boolean interchange) { if (hex.length() == 16) { String high = hex.substring(0, 4); String high1 = hex.substring(4, 8); String low = hex.substring(8, 12); String low1 = hex.substring(12, 16); if (interchange) { hex = low1 + low + high1 + high;//高低位互换 } long ieee754Int = Long.parseUnsignedLong(hex, 16); double realValue = Double.longBitsToDouble(ieee754Int); return realValue; } else { throw new RuntimeException("待解析字符串必须是16位16进制字符"); } } }
java modbus 32位浮点数解析
最新推荐文章于 2024-07-30 03:31:27 发布