Java IEEE754 工具类

IEEE754转换类

package com.xxx.xxx.utils;

import android.annotation.SuppressLint;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;

/**
 * Author:Think
 * Time:2021/2/3 16:58
 * Description:This is IEEE754
 */
public class IEEE754 {

    /**
     * @Desc: IEEE754标准(四字节转浮点数),公式转换
     * @Author: Aries.hu
     * @Date: 2021/2/3 10:14
     */
    public static float hex2FloatIeee(byte[] hex){
        String hexStr = DataTransform.bytesToHex(hex);
        StringBuilder binaryStr = new StringBuilder();
        for(int i=0;i< hexStr.length();i+=2){
            String a = hexStr.substring(i,i+2);
            int c = Integer.parseInt(a,16);
            @SuppressLint("DefaultLocale") String item = String.format("%08d",Integer.parseInt(Integer.toBinaryString(c)));
            binaryStr.append(item);
        }
        int n =  Integer.parseInt(binaryStr.substring(1,9),2);
        String mStr = binaryStr.substring(9,binaryStr.length()-1);
        double sum = 0;
        for(int i =1;i<=mStr.length();i++){
            if(mStr.charAt(i-1)=='1'){
                sum = sum+Math.pow(0.5,i);
            }
        }
        float v = (float) ((Math.pow(2, n - 127)) * (1 + sum));
        return v;
    }

    /**
     * @Desc: IEEE754标准(四字节转浮点数)调用JDK接口转换
     * @Author: Aries.hu
     * @Date: 2021/2/5 10:23
     */
    public static float hex2floatIeeeApi(byte[] bytes, boolean reverse){
        float result;
        if(reverse){
            //bytes = DataTransform.bytesArrayReverse(bytes);
            result = ByteBuffer.wrap(bytes).order(ByteOrder.BIG_ENDIAN).getFloat();
        }

        /****************************此方式数据太大会超出int类型范围****************************/
        //String hex= DataTransform.encodeHexStr(bytes, true);
        //return Float.intBitsToFloat(Integer.valueOf(hex, 16));
        /****************************此方式数据太大会超出int类型范围****************************/

        result = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN).getFloat();

        return result;
    }

    /**
     * @Desc: IEEE754标准(浮点数转四字节)调用JDK接口转换
     * @Author: Aries.hu
     * @Date: 2021/2/5 11:57
     */
    public static byte[] float2hexIeeeApi(float f){
        int intBits = Float.floatToRawIntBits(f);
        return DataTransform.intToByteArray(intBits);
    }

}

 

数据转换类

 

package com.example.d23.utils;

/**
 * Author:Think
 * Time:2021/2/3 10:14
 * Description:This is DataTransfor
 */
public class DataTransform {

    //https://www.iteye.com/blog/aub-1129228
    //https://github.com/FirebirdSQL/decimal-java

    /**
     * 用于建立十六进制字符的输出的小写字符数组
     */
    private static final char[] DIGITS_LOWER = { '0', '1', '2', '3', '4', '5',
            '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };

    /**
     * 用于建立十六进制字符的输出的大写字符数组
     */
    private static final char[] DIGITS_UPPER = { '0', '1', '2', '3', '4', '5',
            '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };

    /**
     * @Desc: 字节转十六进制字符串
     * @Author: Aries.hu
     * @Date: 2021/2/3 11:19
     */
    public static String byteToHex(byte b) {
        String hex = Integer.toHexString(b & 0xFF);
        if (hex.length() < 2) {
            hex = "0" + hex;
        }
        return hex;
    }

    /**
     * @Desc: 字节数组转字符串
     * @Author: Aries.hu
     * @Date: 2021/2/3 11:19
     */
    public static String bytesToHex(byte[] bytes) {
        StringBuilder sbuffer = new StringBuilder();
        for (byte aByte : bytes) {
            String hex = Integer.toHexString(aByte & 0xFF);
            if (hex.length() < 2) {
                sbuffer.append(0);
            }
            sbuffer.append(hex);
        }
        return sbuffer.toString();
    }

    /**
     * @Desc: 数组倒序
     * @Author: Aries.hu
     * @Date: 2021/2/3 15:15
     */
    public static byte[] bytesArrayReverse(byte[] src){
        byte temp = 0;
        int len = src.length;
        for (int i = 0; i < len / 2; i++) {
            temp = src[i];
            src[i] = src[len - i - 1];
            src[len - i - 1] = temp;
        }

        return src;
    }
    
    /**
     * @Desc: byte数组转换为二进制字符串,每个字节以","隔开
     * @Author: Aries.hu
     * @Date: 2021/2/3 15:47
     */
    public static String byteArrToBinStr(byte[] b) {
        StringBuffer result = new StringBuffer();
        for (int i = 0; i < b.length; i++) {
            result.append(Long.toString(b[i] & 0xff, 2) + ",");
        }
        return result.toString().substring(0, result.length() - 1);
    }

    /**
     * @Desc: 二进制字符串转换为byte数组,8位一个字节
     * @Author: Aries.hu
     * @Date: 2021/2/3 15:48
     */
    public static byte[] binStrToByteArr(String binStr) {

        if("".equals(binStr)){
            return new byte[0];
        }

        final int bits = 8;
        int str_len = 0;
        int byte_len = 0;

        StringBuilder binStrBuilder = new StringBuilder(binStr);
        while (binStrBuilder.length() < 32){
            binStrBuilder.append("0");
        }
        binStr = binStrBuilder.toString();
        str_len = binStr.length();

        System.out.println(binStr);

        if(str_len % bits == 0){
            byte_len = str_len / bits;
        }

        byte[] b = new byte[byte_len];
        int index = 0;

        for(int i=0;i<str_len;i+=bits){
            String s = binStr.substring(i, i+bits);
            System.out.println(s);
            b[index] = bit2byte(s);
            index++;
        }

        return b;
    }

    protected static String encodeHexStr(byte[] data, char[] toDigits) {
        return new String(encodeHex(data, toDigits));
    }

    /**
     * @Desc: 字节数组转十六进制字符串
     * @Author: Aries.hu
     * @Date: 2021/2/5 11:48
     */
    public static String encodeHexStr(byte[] data, boolean toLowerCase) {
        return encodeHexStr(data, toLowerCase ? DIGITS_LOWER : DIGITS_UPPER);
    }

    /**
     * @Desc: 将字节数组转换为十六进制字符数组
     * @Author: Aries.hu
     * @Date: 2021/2/5 11:47
     */
    protected static char[] encodeHex(byte[] data, char[] toDigits) {
        int l = data.length;
        char[] out = new char[l << 1];
        // two characters form the hex value.
        for (int i = 0, j = 0; i < l; i++) {
            out[j++] = toDigits[(0xF0 & data[i]) >>> 4];
            out[j++] = toDigits[0x0F & data[i]];
        }
        return out;
    }

    public static byte bit2byte(String bString){
        byte result=0;
        for(int i=bString.length()-1,j=0;i>=0;i--,j++){
            result+=(Byte.parseByte(bString.charAt(i)+"")*Math.pow(2, j));
        }
        return result;
    }

    /**
     * @Desc: 字节数组转二进制字符串
     * @Author: Aries.hu
     * @Date: 2021/2/3 10:24
     */
    public static String bytes2BinaryStr(byte[] bytes){
        StringBuilder binaryStr = new StringBuilder();
        for (byte aByte : bytes) {
            String str = Integer.toBinaryString((aByte & 0xFF) + 0x100).substring(1);
            binaryStr.append(str);
        }
        return binaryStr.toString();
    }

    /**
     * @Desc: int转byte数组
     * @Author: Aries.hu
     * @Date: 2021/2/5 21:21
     */
    public static byte[] intToByteArray(int i) {
        byte[] result = new byte[4];
        // 由高位到低位
        result[0] = (byte) ((i >> 24) & 0xFF);
        result[1] = (byte) ((i >> 16) & 0xFF);
        result[2] = (byte) ((i >> 8) & 0xFF);
        result[3] = (byte) (i & 0xFF);
        return result;
    }
}

 

调用

 

package com.example.d23;

import com.example.d23.utils.DataTransform;
import com.example.d23.utils.IEEE754;

import org.junit.Test;

import static org.junit.Assert.assertEquals;

/**
 * Author:Think
 * Time:2021/2/3 11:21
 * Description:This is DataTransforTest
 */
public class DataTransformTest {
    @Test
    public void bytesToFloat(){
        byte[] bytes = {(byte) 0x7B, (byte) 0x20, (byte) 0xB1, (byte) 0x2C};
        float result = IEEE754.hex2floatIeeeApi(bytes, true);
        System.out.println(result);
    }

    @Test
    public void floatToBytes(){
        float f = 5.0342486E-12f;
        byte[] result = IEEE754.float2hexIeeeApi(f);
        System.out.println(DataTransform.bytesToHex(result));
    }
}
posted @ 2021-02-05 21:47  Yan327  阅读(985)  评论(0编辑  收藏  举报