JAVA字节数组转常见类型

本文是对工作中使用udp接收数据后,根据协议对字节数组进行解析,所做的一个记录。

import io.netty.buffer.Unpooled;
import java.text.DecimalFormat;



public class ByteUtil {



    /**
     * 大小端 高低位转换
     *
     * @param bytes
     * @return
     */
    public static byte[] reByte(byte[] bytes) {
        int n = bytes.length;
        byte[] b = new byte[n];
        for (int i = 0; i < n; i++) {
            b[i] = bytes[n - 1 - i];
        }
        return b;
    }


    /**
     * 去掉byte[]中填充的0 转为String
     * @param buffer
     * @return
     */
    public static String byteToString(byte[] buffer) {
        try {
            int length = 0;
            for (int i = 0; i < buffer.length; ++i) {
                if (buffer[i] == 0) {
                    length = i;
                    break;
                }
            }
            return new String(buffer, 0, length, "UTF-8");
        } catch (Exception e) {
            return "";
        }
    }

    /**
     * 截取 字节数组
     *
     * @param bytes  源
     * @param start  起始位置
     * @param length 长度
     * @return
     */
    public static byte[] byteToByte(byte[] bytes, int start, int length) {
        byte[] nByte = new byte[length];
        System.arraycopy(bytes, start, nByte, 0, length);
        return nByte;
    }

    /**
     * 4字节bytes数组转为无符号long
     *
     * @param bytes1
     * @return
     */
    public static long byteToUInt(byte[] bytes1) {
    	//高低位转换 看协议是否需要
        byte[] bytes = reByte(bytes1);
        return Unpooled.wrappedBuffer(bytes).readUnsignedInt();
    }

    /**
     * 4字节bytes数组转为int
     *
     * @param bytes1
     * @return
     */
    public static int byteToInt(byte[] bytes1) {
        //高低位转换 看协议是否需要
        byte[] bytes = reByte(bytes1);
        byte[] a = new byte[4];
        int i = a.length - 1;
        int j = bytes.length - 1;
        for (; i >= 0; i--, j--) {
            if (j >= 0) {
                a[i] = bytes[j];
            } else {
                a[i] = 0;
            }
        }
        int v0 = (a[0] & 0xff) << 24;
        int v1 = (a[1] & 0xff) << 16;
        int v2 = (a[2] & 0xff) << 8;
        int v3 = (a[3] & 0xff);
        return v0 + v1 + v2 + v3;
    }

    /**
     * 8字节bytes数组转为long
     *
     * @param bytes1
     * @return
     */
    public static long byteToLong(byte[] bytes1) {
    	//高低位转换 看协议是否需要
        byte[] bytes = reByte(bytes1);
        byte[] b = new byte[8];
        int i = b.length - 1;
        int j = bytes.length - 1;
        for (; i >= 0; i--, j--) {
            if (j >= 0) {
                b[i] = bytes[j];
            } else {
                b[i] = 0;
            }
        }
        long v0 = (long) (b[0] & 0xff) << 56;
        long v1 = (long) (b[1] & 0xff) << 48;
        long v2 = (long) (b[2] & 0xff) << 40;
        long v3 = (long) (b[3] & 0xff) << 32;
        long v4 = (long) (b[4] & 0xff) << 24;
        long v5 = (long) (b[5] & 0xff) << 16;
        long v6 = (long) (b[6] & 0xff) << 8;
        long v7 = (long) (b[7] & 0xff);
        return v0 + v1 + v2 + v3 + v4 + v5 + v6 + v7;
    }

    /**
     * 2字节bytes数组转为short
     *
     * @param bytes
     * @return
     */
    public static short byteToShort(byte[] bytes) {
        return (short) (((bytes[1] << 8) | bytes[0] & 0xff));
    }

    /**
     * 2字节bytes数组转换为无符号短整型
     *
     * @param bytes
     * @return
     */
    public static int byteToInt2(byte[] bytes) {
        byte[] newBytes = new byte[bytes.length];
        if (bytes.length == 2) {
            newBytes[1] = bytes[0];
            newBytes[0] = bytes[1];
        } else {
            newBytes = bytes;
        }
        return Unpooled.wrappedBuffer(newBytes).readUnsignedShort();

    }
    public static int[] byteToInt2S(byte[] bytes, int num) {
        int[] ints = new int[num];
        for (int i = 0; i < num; i++) {
            byte[] date = byteToByte(bytes, i * 2, 2);
            int value = byteToInt2(date);
            ints[i] = value;
        }
        return ints;
    }
    public static int[] byteToInt2s(byte[] bytes) {
        int num = bytes.length / 2;
        int[] ints = byteToInt2S(bytes, num);
        return ints;
    }

    public static double[] intToDouble(int[] ints) {
        int length = ints.length;
        double[] doubles = new double[length];
        for (int i = 0; i < length;i++){
            doubles[i] = ints[i] * 0.01;
        }
        return doubles;
    }

    /**
     * byte ->int - >double  (int *0.01)
     * @param bytes
     * @return
     */
    public static double[] byteToIntToDouble( byte[] bytes) {
        int[] ints = byteToInt2s(bytes);
        double[] doubles = intToDouble(ints);
        return doubles;
    }


    /**
     * 将单字节byte转int
     */
    public static int byteToInt1(byte bytes) {
        return bytes & 0xff;
    }

    /**
     * 将单字节byte转int->转char
     */
    public static char byteToChar(byte[] bytes) {
        return (char) (bytes[0] & 0xff);
    }

    /**
     * 字节转16进制字符串
     *
     * @param bytes
     * @return
     */
    public static String byteToHex(byte[] bytes) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < bytes.length; i++) {
            int v = bytes[i] & 0xFF;

            String hv = Integer.toHexString(v);
            if (hv.length() ==1){
                hv = "0" + hv;
            }
            sb.insert(0, hv);
        }

        return sb.toString().toUpperCase();
    }

    /**
     * 根据个数解析double[]
     * 取 8 * num 的有效数据
     *
     * @param bytes
     * @param num
     * @return
     */
    public static double[] byteToDoubles(byte[] bytes, int num) {
        double[] doubles = new double[num];
        for (int i = 0; i < num; i++) {
            byte[] date = byteToByte(bytes, i * 8, 8);
            double value = ByteToDouble(date);
            doubles[i] = value;
        }
        return doubles;
    }

    /**
     * 根据个数解析double[]
     * 取 length / 8 个有效数据
     *
     * @param bytes
     * @return
     */
    public static double[] byteToDoubles(byte[] bytes) {
        int num = bytes.length / 8;
        return byteToDoubles(bytes, num);
    }


    /**
     * 4字节bytes数组转为float 
     *
     * @param bytes
     * @return
     */
    public static float ByteToFloat(byte[] bytes) {
        int floatValue = 0;
        for (int i = 0; i < 4; i++) {
            floatValue = floatValue | (bytes[i] & 0xff) << (8 * i);
        }

        return floatValue;
    }

    /**
     * 4字节bytes数组转为float  ???
     *
     * @param bytes
     * @return
     */
    public static float ByteToFloat(byte[] bytes, int num) {
        int floatValue = 0;
        for (int i = 0; i < 4; i++) {
            floatValue = floatValue | (bytes[i] & 0xff) << (8 * i);
        }
        //保留三位小数
        return Float.parseFloat(subAccuracy(Float.intBitsToFloat(floatValue), num));
    }

    /**
     * 八字节bytes数组转为double 
     *
     * @param bytes
     * @return
     */
    public static double ByteToDouble(byte[] bytes) {
        long doubleValue = byteToLong(bytes);
        double v1 = Double.longBitsToDouble(doubleValue);
        return v1;
    }




    /**
     * 八字节bytes数组转为double  
     * 保留小数位数
     *
     * @param bytes
     * @param num   保留小数位数 0-3
     * @return
     */
    public static double ByteToDouble(byte[] bytes, int num) {

        long doubleValue = 0;
        for (int i = 0; i < 8; i++) {
            doubleValue |= ((long) (bytes[i] & 0xff)) << (8 * i);
        }
        //保留小数
        return Double.parseDouble(subAccuracy(Double.longBitsToDouble(doubleValue), num));
    }

    /**
     * 精度保留
     *
     * @param param  值
     * @param length 保留小数的长度
     * @return
     */
    public static String subAccuracy(Object param, int length) {
        String s = "";
        if (length == 0) {
            //不保留小数
            DecimalFormat decimalFormat = new DecimalFormat("0");
            s = decimalFormat.format(param);
        } else if (length == 1) {
            //保留一位小数
            DecimalFormat decimalFormat1 = new DecimalFormat("0.0");
            s = decimalFormat1.format(param);
        } else if (length == 2) {
            //保留两位小数
            DecimalFormat decimalFormat2 = new DecimalFormat("0.00");
            s = decimalFormat2.format(param);
        } else if (length == 3) {
            //保留三位小数
            DecimalFormat decimalFormat3 = new DecimalFormat("0.000");
            s = decimalFormat3.format(param);
        }
        return s;
    }
//
//    /**
//     * 根据要转换的数据类型进行不同的转换
//     *
//     * @param type
//     * @param bytes
//     * @return
//     */
//    public Object byteArrayToTarget(String type, byte[] bytes) {
//        Object object = new Object();
//        //根据不同的类型将byte转换
//        if ("int".equals(type)) {
//            //4字节bytes数组转为int
//            byte[] a = new byte[4];
//            int i = a.length - 1;
//            int j = bytes.length - 1;
//            for (; i >= 0; i--, j--) {
//                if (j >= 0) {
//                    a[i] = bytes[j];
//                } else {
//                    a[i] = 0;
//                }
//            }
//            int v0 = (a[0] & 0xff) << 24;
//            int v1 = (a[1] & 0xff) << 16;
//            int v2 = (a[2] & 0xff) << 8;
//            int v3 = (a[3] & 0xff);
//            return v0 + v1 + v2 + v3;
//        } else if ("uInt".equals(type)) {
//            //4字节bytes数组转为无符号long
//            long l = Unpooled.wrappedBuffer(bytes).readUnsignedInt();
//            return l;
//        } else if ("long".equals(type)) {
//            //8字节bytes数组转为long
//            byte[] b = new byte[8];
//            int i = b.length - 1;
//            int j = bytes.length - 1;
//            for (; i >= 0; i--, j--) {
//                if (j >= 0) {
//                    b[i] = bytes[j];
//                } else {
//                    b[i] = 0;
//                }
//            }
//            long v0 = (long) (b[0] & 0xff) << 56;
//            long v1 = (long) (b[1] & 0xff) << 48;
//            long v2 = (long) (b[2] & 0xff) << 40;
//            long v3 = (long) (b[3] & 0xff) << 32;
//            long v4 = (long) (b[4] & 0xff) << 24;
//            long v5 = (long) (b[5] & 0xff) << 16;
//            long v6 = (long) (b[6] & 0xff) << 8;
//            long v7 = (long) (b[7] & 0xff);
//            return v0 + v1 + v2 + v3 + v4 + v5 + v6 + v7;
//        } else if ("float".equals(type)) {
//            //4字节bytes数组转为float
//            int floatValue = 0;
//            for (int i = 0; i < 4; i++) {
//                floatValue = floatValue | (bytes[i] & 0xff) << (8 * i);
//            }
//            //保留三位小数
//            return subAccuracy(Float.intBitsToFloat(floatValue), 3);
//        } else if ("double".equals(type)) {
//            //八字节bytes数组转为double
//            long doubleValue = 0;
//            for (int i = 0; i < 8; i++) {
//                doubleValue |= ((long) (bytes[i] & 0xff)) << (8 * i);
//            }
//            //保留三位小数
//            return subAccuracy(Double.longBitsToDouble(doubleValue), 3);
//        } else if ("char".equals(type)) {
//            char c = (char) (((bytes[0] & 0xff) << 8) | (bytes[1] & 0xff));
//            int c1 = c;
//            if (c1 >= 32768) {
//                return (int) (-32768 + (c1 - 32768));
//            } else {
//                return c1;
//            }
//        } else if ("binary".equals(type)) {
//            //单字节byte转成八位二进制字符串
//            return Integer.toBinaryString((bytes[0] & 0xff) + 0x100).substring(1);
//        } else if ("short".equals(type)) {
//            //2字节bytes数组转为short
//            return (short) (((bytes[1] << 8) | bytes[0] & 0xff));
//        } else if ("uShort".equals(type)) {
//            //2字节bytes数组转换为无符号int
//            byte[] newBytes = new byte[bytes.length];
//            if (bytes.length == 2) {
//                newBytes[1] = bytes[0];
//                newBytes[0] = bytes[1];
//            } else {
//                newBytes = bytes;
//            }
//            int i = Unpooled.wrappedBuffer(newBytes).readUnsignedShort();
//            return i;
//        } else if ("hex".equals(type)) {
//            //单字节byte转为16进制
//            String result = Integer.toHexString(bytes[0] & 0xff);
//            if (result.length() == 1) {
//                result = '0' + result;
//            }
//            return result.toUpperCase();
//        } else if ("byte".equals(type)) {
//            //将单字节byte转int
//            return bytes[0] & 0xff;
//        }
//        return object;
//    }
//


}

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
### 回答1: 要将字节数组转换为OutputStream,可以使用Java中的ByteArrayOutputStream类。以下是一个示例代码: ```java byte[] bytes = {1, 2, 3, 4, 5}; OutputStream outputStream = new ByteArrayOutputStream(); outputStream.write(bytes); ``` 在这个示例中,我们首先创建一个字节数组(`byte[]`),然后将其写入`ByteArrayOutputStream`中。这个`ByteArrayOutputStream`就是我们想要的`OutputStream`,我们可以在之后的代码中使用它。 ### 回答2: 字节数组转outputstream可以使用ByteArrayOutputStream类来实现。 首先,创建一个ByteArrayOutputStream对象,可以使用无参构造函数创建一个初始为空的对象。 然后,使用write()方法将字节数组写入ByteArrayOutputStream对象中。该方法接受字节数组作为参数,将字节数组的内容写入输出流中。 接下来,可以通过调用toByteArray()方法,将ByteArrayOutputStream对象中的内容转换为字节数组。 最后,可以使用ByteArrayInputStream对象的write()方法将字节数组写入到输出流中。该方法接受字节数组作为参数,将字节数组的内容写入输出流中。 具体示例代码如下: ```java byte[] byteArray = {1, 2, 3, 4, 5}; ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); outputStream.write(byteArray); byte[] resultByteArray = outputStream.toByteArray(); ``` 以上代码将字节数组byteArray写入到了outputStream对象中,并通过调用toByteArray()方法获取转换后的字节数组resultByteArray。 ### 回答3: 字节数组可以转换为OutputStream流的方法有多种。其中一种常见的方法是使用ByteArrayOutputStream类。 使用ByteArrayOutputStream类可以将字节数组转换为OutputStream流。具体步骤如下: 1. 创建一个ByteArrayOutputStream对象:ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); 2. 将字节数组写入到ByteArrayOutputStream对象中:byteArrayOutputStream.write(byteArray); 3. 将ByteArrayOutputStream对象转换为OutputStream流:OutputStream outputStream = new DataOutputStream(byteArrayOutputStream); 这样,字节数组就成功地转换为OutputStream流了。通过OutputStream流,我们可以对字节数组进行进一步的处理,比如写入文件或通过网络传输等。 另外,字节数组还可以通过ByteArrayInputStream类和PipedOutputStream类进行转换。使用ByteArrayInputStream类可以将字节数组转换为InputStream流,而使用PipedOutputStream类则可将字节数组转换为PipedInputStream流。 无论采用哪种方法,都可实现字节数组转换为OutputStream流的功能,便于对字节数组的数据进行进一步处理。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值