‘liusuyi’
2023-12-05 745d5b90be7d8cdb8873b18d18b286fdc4b6913b
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
package com.ard.utils.util;
 
import javax.xml.bind.DatatypeConverter;
import java.io.ByteArrayOutputStream;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.zip.CRC32;
 
/**
 * @Description: 字节工具类
 * @ClassName: byteUtils
 * @Author: 刘苏义
 * @Date: 2023年07月03日15:18
 * @Version: 1.0
 **/
public class ByteUtils {
 
    /**
     * 打印十六进制二进制
     */
    public static String printHexBinary(byte[] bytes) {
        return DatatypeConverter.printHexBinary(bytes);
    }
 
    /**
     * byte数组转中文字符串
     */
    public static String bytesToStringZh(byte[] bytes) {
        //ByteBuffer buffer = ByteBuffer.wrap(bytes); // byteArray 是包含字节数组的变量
        //try {
        //    return new String(buffer.array(), "GBK");
        //} catch (UnsupportedEncodingException e) {
        //    e.printStackTrace();
        //}
        //return "";
        String zhStr = "";
        try {
            int position = ByteUtils.findIndexOfDoubleZero(bytes);
            if (position != -1) {
                byte[] result = new byte[position];
                System.arraycopy(bytes, 0, result, 0, position);
                zhStr = new String(result, "GBK");
            } else {
                zhStr = new String(bytes, "GBK");
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return zhStr;
    }
 
    /**
     * Byte字节转Hex
     *
     * @param b 字节
     * @return Hex
     */
    public static String byteToHex(byte b) {
        String hexString = Integer.toHexString(b & 0xFF);
        //由于十六进制是由0~9、A~F来表示1~16,所以如果Byte转换成Hex后如果是<16,就会是一个字符(比如A=10),通常是使用两个字符来表示16进制位的,
        //假如一个字符的话,遇到字符串11,这到底是1个字节,还是1和1两个字节,容易混淆,如果是补0,那么1和1补充后就是0101,11就表示纯粹的11
        if (hexString.length() < 2) {
            hexString = new StringBuilder(String.valueOf(0)).append(hexString).toString();
        }
        return hexString.toUpperCase();
    }
 
    /**
     * byte数组转float
     */
    public static float bytesToFloat(byte[] bytes) {
        ByteBuffer buffer = ByteBuffer.wrap(bytes);
        return buffer.getFloat();
    }
 
    /**
     * byte数组转整型
     */
    public static int bytesToDecimal(byte[] byteArray) {
        //ByteBuffer buffer = ByteBuffer.wrap(byteArray); // byteArray 是包含字节数组的变量
        //return buffer.getInt();
        int decimalValue = 0;
        for (int i = 0; i < byteArray.length; i++) {
            decimalValue = (decimalValue << 8) | (byteArray[i] & 0xFF);
        }
        return decimalValue;
    }
 
 
    /**
     * byte数组转Double
     */
    public static double bytesToDouble(byte[] byteArray) {
        // 创建一个ByteBuffer
        ByteBuffer buffer = ByteBuffer.wrap(byteArray);
        //设置字节顺序为大端
        buffer.order(ByteOrder.LITTLE_ENDIAN);
        // 从ByteBuffer中获取double值
        double doubleValue = buffer.getDouble();
        return doubleValue;
    }
 
    /**
     * 大端转小端
     */
    public static byte[] toLittleEndian(byte[] bigEndianBytes) {
        byte[] littleEndianBytes = new byte[bigEndianBytes.length];
 
        for (int i = 0; i < bigEndianBytes.length; i++) {
            int j = bigEndianBytes.length - i - 1;
            littleEndianBytes[i] = bigEndianBytes[j];
        }
 
        return littleEndianBytes;
    }
 
    /**
     * 小端转大端
     */
    public static byte[] toBigEndian(byte[] littleEndianBytes) {
        byte[] bigEndianBytes = new byte[littleEndianBytes.length];
        for (int i = 0; i < littleEndianBytes.length; i++) {
            bigEndianBytes[i] = littleEndianBytes[littleEndianBytes.length - 1 - i];
        }
        return bigEndianBytes;
    }
 
    /**
     * int转byte数组
     */
    public static byte[] decimalToBytes(int decimalValue) {
        ByteBuffer buffer = ByteBuffer.allocate(Integer.BYTES);
        buffer.putInt(decimalValue);
        return buffer.array();
    }
 
 
    /**
     * double转byte数组
     */
    public static byte[] doubleToBytes(double d) {
        // 创建一个 ByteBuffer,分配足够的空间来存储一个 float 值
        ByteBuffer buffer = ByteBuffer.allocate(Double.BYTES);
        // 将 float 值写入 ByteBuffer
        buffer.putDouble(d);
        // 获取字节数组
        return buffer.array();
    }
 
    /**
     * float转byte数组
     */
    public static byte[] floatToBytes(float f) {
        // 创建一个 ByteBuffer,分配足够的空间来存储一个 float 值
        ByteBuffer buffer = ByteBuffer.allocate(Float.BYTES);
        // 将 float 值写入 ByteBuffer
        buffer.putFloat(f);
        // 获取字节数组
        return buffer.array();
    }
 
    /**
     * byte数组拼接
     */
    public static byte[] appendArrays(byte[]... arrays) {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        try {
            for (byte[] array : arrays) {
                outputStream.write(array);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return outputStream.toByteArray();
    }
 
    /**
     * byte数组CRC32校验
     */
    public static byte[] parseCrc32(byte[] bytes) {
        CRC32 crc32 = new CRC32();
        crc32.update(bytes);
        bytes = ByteUtils.decimalToBytes((int) crc32.getValue());
        bytes = ByteUtils.toBigEndian(bytes);
        // System.out.print("校验:"+DatatypeConverter.printHexBinary(bytes));//打印crc32的校验值
        return bytes;
    }
    /**
     * byte转二进制字符串
     */
    public static String byteToBitString(byte b) {
        return String.format("%8s", Integer.toBinaryString(b & 0xFF)).replace(' ', '0');
    }
    /**
     * 去除包头包尾
     * 刘苏义
     * 2023/7/4 11:24
     */
    public static byte[] removeHeaderAndFooter(byte[] data, int headerLength, int footerLength) {
        int payloadLength = data.length - headerLength - footerLength;
        byte[] payload = new byte[payloadLength];
        System.arraycopy(data, headerLength, payload, 0, payloadLength);
        return payload;
    }
 
    /**
     * 去除包头包尾crc校验
     * 刘苏义
     * 2023/7/4 11:24
     */
    public static byte[] removeHeaderFooterAndCRC(byte[] data, int headerLength, int footerLength, int crcLength) {
        int payloadLength = data.length - headerLength - footerLength - crcLength;
        byte[] payload = new byte[payloadLength];
        System.arraycopy(data, headerLength, payload, 0, payloadLength);
        return payload;
    }
 
    /**
     * 获取后面的字节数组
     * 刘苏义
     * 2023/7/4 11:24
     */
    public static byte[] getLastBytes(byte[] data, int count) {
        int startIndex = data.length - count;
        byte[] lastBytes = new byte[count];
        System.arraycopy(data, startIndex, lastBytes, 0, count);
        return lastBytes;
    }
 
    /**
     * 找到00的索引位置
     */
    public static int findIndexOfDoubleZero(byte[] bytes) {
        for (int i = 0; i < bytes.length - 1; i++) {
            if (bytes[i] == 0x00) {
                return i;
            }
        }
        return -1;
    }
}