java modbus 32位浮点数解析

原文连接: https://blog.csdn.net/huoyizu/article/details/49126063

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进制字符");
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值